1 /*
   2  * Copyright (c) 2016, 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 package requires;
  24 
  25 import java.io.BufferedInputStream;
  26 import java.io.BufferedReader;
  27 import java.io.FileInputStream;
  28 import java.io.IOException;
  29 import java.io.InputStream;
  30 import java.io.InputStreamReader;
  31 import java.nio.file.Files;
  32 import java.nio.file.Path;
  33 import java.nio.file.Paths;
  34 import java.nio.file.StandardOpenOption;
  35 import java.util.ArrayList;
  36 import java.util.HashMap;
  37 import java.util.List;
  38 import java.util.Map;
  39 import java.util.Properties;
  40 import java.util.concurrent.Callable;
  41 import java.util.concurrent.TimeUnit;
  42 import java.util.function.Supplier;
  43 import java.util.regex.Matcher;
  44 import java.util.regex.Pattern;
  45 
  46 import sun.hotspot.code.Compiler;
  47 import sun.hotspot.cpuinfo.CPUInfo;
  48 import sun.hotspot.gc.GC;
  49 import sun.hotspot.WhiteBox;
  50 import jdk.test.lib.Platform;
  51 
  52 /**
  53  * The Class to be invoked by jtreg prior Test Suite execution to
  54  * collect information about VM.
  55  * Do not use any APIs that may not be available in all target VMs.
  56  * Properties set by this Class will be available in the @requires expressions.
  57  */
  58 public class VMProps implements Callable<Map<String, String>> {
  59     // value known to jtreg as an indicator of error state
  60     private static final String ERROR_STATE = "__ERROR__";
  61 
  62     private static final WhiteBox WB = WhiteBox.getWhiteBox();
  63 
  64     private static class SafeMap {
  65         private final Map<String, String> map = new HashMap<>();
  66 
  67         public void put(String key, Supplier<String> s) {
  68             String value;
  69             try {
  70                 value = s.get();
  71             } catch (Throwable t) {
  72                 System.err.println("failed to get value for " + key);
  73                 t.printStackTrace(System.err);
  74                 value = ERROR_STATE + t;
  75             }
  76             map.put(key, value);
  77         }
  78     }
  79 
  80     /**
  81      * Collects information about VM properties.
  82      * This method will be invoked by jtreg.
  83      *
  84      * @return Map of property-value pairs.
  85      */
  86     @Override
  87     public Map<String, String> call() {
  88         SafeMap map = new SafeMap();
  89         map.put("vm.flavor", this::vmFlavor);
  90         map.put("vm.compMode", this::vmCompMode);
  91         map.put("vm.bits", this::vmBits);
  92         map.put("vm.flightRecorder", this::vmFlightRecorder);
  93         map.put("vm.simpleArch", this::vmArch);
  94         map.put("vm.debug", this::vmDebug);
  95         map.put("vm.jvmci", this::vmJvmci);
  96         map.put("vm.emulatedClient", this::vmEmulatedClient);
  97         // vm.hasSA is "true" if the VM contains the serviceability agent
  98         // and jhsdb.
  99         map.put("vm.hasSA", this::vmHasSA);
 100         // vm.hasSAandCanAttach is "true" if the VM contains the serviceability agent
 101         // and jhsdb and it can attach to the VM.
 102         map.put("vm.hasSAandCanAttach", this::vmHasSAandCanAttach);
 103         // vm.hasJFR is "true" if JFR is included in the build of the VM and
 104         // so tests can be executed.
 105         map.put("vm.hasJFR", this::vmHasJFR);
 106         map.put("vm.cpu.features", this::cpuFeatures);
 107         map.put("vm.rtm.cpu", this::vmRTMCPU);
 108         map.put("vm.rtm.compiler", this::vmRTMCompiler);
 109         map.put("vm.aot", this::vmAOT);
 110         map.put("vm.aot.enabled", this::vmAotEnabled);
 111         // vm.cds is true if the VM is compiled with cds support.
 112         map.put("vm.cds", this::vmCDS);
 113         map.put("vm.cds.custom.loaders", this::vmCDSForCustomLoaders);
 114         map.put("vm.cds.archived.java.heap", this::vmCDSForArchivedJavaHeap);
 115         // vm.graal.enabled is true if Graal is used as JIT
 116         map.put("vm.graal.enabled", this::isGraalEnabled);
 117         map.put("vm.compiler1.enabled", this::isCompiler1Enabled);
 118         map.put("vm.compiler2.enabled", this::isCompiler2Enabled);
 119         map.put("docker.support", this::dockerSupport);
 120         map.put("vm.musl", this::isMusl);
 121         map.put("release.implementor", this::implementor);
 122         map.put("test.vm.gc.nvdimm", this::isNvdimmTestEnabled);
 123         vmGC(map); // vm.gc.X = true/false
 124         vmOptFinalFlags(map);
 125 
 126         dump(map.map);
 127         return map.map;
 128     }
 129 
 130     /**
 131      * Print a stack trace before returning error state;
 132      * Used by the various helper functions which parse information from
 133      * VM properties in the case where they don't find an expected property
 134      * or a property doesn't conform to an expected format.
 135      *
 136      * @return {@link #ERROR_STATE}
 137      */
 138     private String errorWithMessage(String message) {
 139         new Exception(message).printStackTrace();
 140         return ERROR_STATE + message;
 141     }
 142 
 143     /**
 144      * @return vm.simpleArch value of "os.simpleArch" property of tested JDK.
 145      */
 146     protected String vmArch() {
 147         String arch = System.getProperty("os.arch");
 148         if (arch.equals("x86_64") || arch.equals("amd64")) {
 149             return "x64";
 150         } else if (arch.contains("86")) {
 151             return "x86";
 152         } else {
 153             return arch;
 154         }
 155     }
 156 
 157     /**
 158      * @return VM type value extracted from the "java.vm.name" property.
 159      */
 160     protected String vmFlavor() {
 161         // E.g. "Java HotSpot(TM) 64-Bit Server VM"
 162         String vmName = System.getProperty("java.vm.name");
 163         if (vmName == null) {
 164             return errorWithMessage("Can't get 'java.vm.name' property");
 165         }
 166 
 167         Pattern startP = Pattern.compile(".* (\\S+) VM");
 168         Matcher m = startP.matcher(vmName);
 169         if (m.matches()) {
 170             return m.group(1).toLowerCase();
 171         }
 172         return errorWithMessage("Can't get VM flavor from 'java.vm.name'");
 173     }
 174 
 175     /**
 176      * @return VM compilation mode extracted from the "java.vm.info" property.
 177      */
 178     protected String vmCompMode() {
 179         // E.g. "mixed mode"
 180         String vmInfo = System.getProperty("java.vm.info");
 181         if (vmInfo == null) {
 182             return errorWithMessage("Can't get 'java.vm.info' property");
 183         }
 184         vmInfo = vmInfo.toLowerCase();
 185         if (vmInfo.contains("mixed mode")) {
 186             return "Xmixed";
 187         } else if (vmInfo.contains("compiled mode")) {
 188             return "Xcomp";
 189         } else if (vmInfo.contains("interpreted mode")) {
 190             return "Xint";
 191         } else {
 192             return errorWithMessage("Can't get compilation mode from 'java.vm.info'");
 193         }
 194     }
 195 
 196     /**
 197      * @return VM bitness, the value of the "sun.arch.data.model" property.
 198      */
 199     protected String vmBits() {
 200         String dataModel = System.getProperty("sun.arch.data.model");
 201         if (dataModel != null) {
 202             return dataModel;
 203         } else {
 204             return errorWithMessage("Can't get 'sun.arch.data.model' property");
 205         }
 206     }
 207 
 208     /**
 209      * @return "true" if Flight Recorder is enabled, "false" if is disabled.
 210      */
 211     protected String vmFlightRecorder() {
 212         Boolean isFlightRecorder = WB.getBooleanVMFlag("FlightRecorder");
 213         String startFROptions = WB.getStringVMFlag("StartFlightRecording");
 214         if (isFlightRecorder != null && isFlightRecorder) {
 215             return "true";
 216         }
 217         if (startFROptions != null && !startFROptions.isEmpty()) {
 218             return "true";
 219         }
 220         return "false";
 221     }
 222 
 223     /**
 224      * @return debug level value extracted from the "jdk.debug" property.
 225      */
 226     protected String vmDebug() {
 227         String debug = System.getProperty("jdk.debug");
 228         if (debug != null) {
 229             return "" + debug.contains("debug");
 230         } else {
 231             return errorWithMessage("Can't get 'jdk.debug' property");
 232         }
 233     }
 234 
 235     /**
 236      * @return true if VM supports JVMCI and false otherwise
 237      */
 238     protected String vmJvmci() {
 239         // builds with jvmci have this flag
 240         return "" + (WB.getBooleanVMFlag("EnableJVMCI") != null);
 241     }
 242 
 243     /**
 244      * @return true if VM runs in emulated-client mode and false otherwise.
 245      */
 246     protected String vmEmulatedClient() {
 247         String vmInfo = System.getProperty("java.vm.info");
 248         if (vmInfo == null) {
 249             return errorWithMessage("Can't get 'java.vm.info' property");
 250         }
 251         return "" + vmInfo.contains(" emulated-client");
 252     }
 253 
 254     /**
 255      * @return supported CPU features
 256      */
 257     protected String cpuFeatures() {
 258         return CPUInfo.getFeatures().toString();
 259     }
 260 
 261     /**
 262      * For all existing GC sets vm.gc.X property.
 263      * Example vm.gc.G1=true means:
 264      *    VM supports G1
 265      *    User either set G1 explicitely (-XX:+UseG1GC) or did not set any GC
 266      *
 267      * @param map - property-value pairs
 268      */
 269     protected void vmGC(SafeMap map) {
 270         for (GC gc: GC.values()) {
 271             map.put("vm.gc." + gc.name(),
 272                     () -> "" + (gc.isSupported()
 273                             && (gc.isSelected() || GC.isSelectedErgonomically())));
 274         }
 275     }
 276 
 277     /**
 278      * Selected final flag.
 279      *
 280      * @param map - property-value pairs
 281      * @param flagName - flag name
 282      */
 283     private void vmOptFinalFlag(SafeMap map, String flagName) {
 284         map.put("vm.opt.final." + flagName,
 285                 () -> String.valueOf(WB.getBooleanVMFlag(flagName)));
 286     }
 287 
 288     /**
 289      * Selected sets of final flags.
 290      *
 291      * @param map - property-value pairs
 292      */
 293     protected void vmOptFinalFlags(SafeMap map) {
 294         vmOptFinalFlag(map, "ClassUnloading");
 295         vmOptFinalFlag(map, "UseCompressedOops");
 296         vmOptFinalFlag(map, "EnableJVMCI");
 297         vmOptFinalFlag(map, "EliminateAllocations");
 298     }
 299 
 300     /**
 301      * @return "true" if VM has a serviceability agent.
 302      */
 303     protected String vmHasSA() {
 304         return "" + Platform.hasSA();
 305     }
 306 
 307     /**
 308      * @return "true" if VM has a serviceability agent and it can
 309      * attach to the VM.
 310      */
 311     protected String vmHasSAandCanAttach() {
 312         try {
 313             return "" + Platform.shouldSAAttach();
 314         } catch (IOException e) {
 315             e.printStackTrace();
 316             return errorWithMessage("Checking whether SA can attach to the VM failed.:" + e);
 317         }
 318     }
 319 
 320     /**
 321      * @return "true" if the VM is compiled with Java Flight Recorder (JFR)
 322      * support.
 323      */
 324     protected String vmHasJFR() {
 325         return "" + WB.isJFRIncludedInVmBuild();
 326     }
 327 
 328     /**
 329      * @return true if compiler in use supports RTM and false otherwise.
 330      */
 331     protected String vmRTMCompiler() {
 332         boolean isRTMCompiler = false;
 333 
 334         if (Compiler.isC2Enabled() &&
 335             (Platform.isX86() || Platform.isX64() || Platform.isPPC())) {
 336             isRTMCompiler = true;
 337         }
 338         return "" + isRTMCompiler;
 339     }
 340 
 341     /**
 342      * @return true if VM runs RTM supported CPU and false otherwise.
 343      */
 344     protected String vmRTMCPU() {
 345         return "" + CPUInfo.hasFeature("rtm");
 346     }
 347 
 348     /**
 349      * @return true if VM supports AOT and false otherwise
 350      */
 351     protected String vmAOT() {
 352         // builds with aot have jaotc in <JDK>/bin
 353         Path bin = Paths.get(System.getProperty("java.home"))
 354                         .resolve("bin");
 355         Path jaotc;
 356         if (Platform.isWindows()) {
 357             jaotc = bin.resolve("jaotc.exe");
 358         } else {
 359             jaotc = bin.resolve("jaotc");
 360         }
 361         return "" + Files.exists(jaotc);
 362     }
 363 
 364     /*
 365      * @return true if there is at least one loaded AOT'ed library.
 366      */
 367     protected String vmAotEnabled() {
 368         return "" + (WB.aotLibrariesCount() > 0);
 369     }
 370 
 371     /**
 372      * Check for CDS support.
 373      *
 374      * @return true if CDS is supported by the VM to be tested.
 375      */
 376     protected String vmCDS() {
 377         return "" + WB.isCDSIncludedInVmBuild();
 378     }
 379 
 380     /**
 381      * Check for CDS support for custom loaders.
 382      *
 383      * @return true if CDS provides support for customer loader in the VM to be tested.
 384      */
 385     protected String vmCDSForCustomLoaders() {
 386         return "" + ("true".equals(vmCDS()) && Platform.areCustomLoadersSupportedForCDS());
 387     }
 388 
 389     /**
 390      * Check for CDS support for archived Java heap regions.
 391      *
 392      * @return true if CDS provides support for archive Java heap regions in the VM to be tested.
 393      */
 394     protected String vmCDSForArchivedJavaHeap() {
 395         return "" + ("true".equals(vmCDS()) && WB.isJavaHeapArchiveSupported());
 396     }
 397 
 398     /**
 399      * Check if Graal is used as JIT compiler.
 400      *
 401      * @return true if Graal is used as JIT compiler.
 402      */
 403     protected String isGraalEnabled() {
 404         return "" + Compiler.isGraalEnabled();
 405     }
 406 
 407     /**
 408      * Check if Compiler1 is present.
 409      *
 410      * @return true if Compiler1 is used as JIT compiler, either alone or as part of the tiered system.
 411      */
 412     protected String isCompiler1Enabled() {
 413         return "" + Compiler.isC1Enabled();
 414     }
 415 
 416     /**
 417      * Check if Compiler2 is present.
 418      *
 419      * @return true if Compiler2 is used as JIT compiler, either alone or as part of the tiered system.
 420      */
 421     protected String isCompiler2Enabled() {
 422         return "" + Compiler.isC2Enabled();
 423     }
 424 
 425    /**
 426      * A simple check for docker support
 427      *
 428      * @return true if docker is supported in a given environment
 429      */
 430     protected String dockerSupport() {
 431         boolean isSupported = false;
 432         if (Platform.isLinux()) {
 433            // currently docker testing is only supported for Linux,
 434            // on certain platforms
 435 
 436            String arch = System.getProperty("os.arch");
 437 
 438            if (Platform.isX64()) {
 439               isSupported = true;
 440            } else if (Platform.isAArch64()) {
 441               isSupported = true;
 442            } else if (Platform.isS390x()) {
 443               isSupported = true;
 444            } else if (arch.equals("ppc64le")) {
 445               isSupported = true;
 446            }
 447         }
 448 
 449         if (isSupported) {
 450            try {
 451               isSupported = checkDockerSupport();
 452            } catch (Exception e) {
 453               isSupported = false;
 454            }
 455          }
 456 
 457         return "" + isSupported;
 458     }
 459 
 460     private boolean checkDockerSupport() throws IOException, InterruptedException {
 461         ProcessBuilder pb = new ProcessBuilder("docker", "ps");
 462         Process p = pb.start();
 463         p.waitFor(10, TimeUnit.SECONDS);
 464 
 465         return (p.exitValue() == 0);
 466     }
 467 
 468     /**
 469      * Check if we run with musl libc.
 470      *
 471      * @return true if we run with musl libc.
 472      */
 473     protected String isMusl() {
 474         try {
 475             ProcessBuilder pb = new ProcessBuilder("ldd", "--version");
 476             pb.redirectErrorStream(true);
 477             final Process p = pb.start();
 478             BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
 479             String line = br.readLine();
 480             if (line != null && line.contains("musl")) {
 481                 return "true";
 482             }
 483         } catch (Exception e) {
 484         }
 485         return "false";
 486     }
 487 
 488     private String implementor() {
 489         try (InputStream in = new BufferedInputStream(new FileInputStream(
 490                 System.getProperty("java.home") + "/release"))) {
 491             Properties properties = new Properties();
 492             properties.load(in);
 493             String implementorProperty = properties.getProperty("IMPLEMENTOR");
 494             if (implementorProperty != null) {
 495                 return implementorProperty.replace("\"", "");
 496             }
 497             return errorWithMessage("Can't get 'IMPLEMENTOR' property from 'release' file");
 498         } catch (IOException e) {
 499             e.printStackTrace();
 500             return errorWithMessage("Failed to read 'release' file " + e);
 501         }
 502     }
 503 
 504     private String isNvdimmTestEnabled() {
 505         String isEnabled = System.getenv("TEST_VM_GC_NVDIMM");
 506         return "" + "true".equalsIgnoreCase(isEnabled);
 507     }
 508 
 509     /**
 510      * Dumps the map to the file if the file name is given as the property.
 511      * This functionality could be helpful to know context in the real
 512      * execution.
 513      *
 514      * @param map
 515      */
 516     protected static void dump(Map<String, String> map) {
 517         String dumpFileName = System.getProperty("vmprops.dump");
 518         if (dumpFileName == null) {
 519             return;
 520         }
 521         List<String> lines = new ArrayList<>();
 522         map.forEach((k, v) -> lines.add(k + ":" + v));
 523         try {
 524             Files.write(Paths.get(dumpFileName), lines,
 525                     StandardOpenOption.APPEND, StandardOpenOption.CREATE);
 526         } catch (IOException e) {
 527             throw new RuntimeException("Failed to dump properties into '"
 528                     + dumpFileName + "'", e);
 529         }
 530     }
 531 
 532     /**
 533      * This method is for the testing purpose only.
 534      *
 535      * @param args
 536      */
 537     public static void main(String args[]) {
 538         Map<String, String> map = new VMProps().call();
 539         map.forEach((k, v) -> System.out.println(k + ": '" + v + "'"));
 540     }
 541 }