1 /*
  2  * Copyright (c) 2016, 2023, 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 package requires;
 25 
 26 import java.io.BufferedInputStream;
 27 import java.io.FileInputStream;
 28 import java.io.IOException;
 29 import java.io.InputStream;
 30 import java.io.File;
 31 import java.nio.charset.Charset;
 32 import java.nio.file.Files;
 33 import java.nio.file.Path;
 34 import java.nio.file.Paths;
 35 import java.nio.file.StandardOpenOption;
 36 import java.time.Instant;
 37 import java.util.ArrayList;
 38 import java.util.Collections;
 39 import java.util.HashMap;
 40 import java.util.List;
 41 import java.util.Map;
 42 import java.util.Properties;
 43 import java.util.Set;
 44 import java.util.concurrent.Callable;
 45 import java.util.concurrent.TimeUnit;
 46 import java.util.function.Predicate;
 47 import java.util.function.Supplier;
 48 import java.util.regex.Matcher;
 49 import java.util.regex.Pattern;
 50 import java.util.stream.Collectors;
 51 import java.util.stream.Stream;
 52 
 53 import jdk.internal.foreign.CABI;
 54 import jdk.test.whitebox.code.Compiler;
 55 import jdk.test.whitebox.cpuinfo.CPUInfo;
 56 import jdk.test.whitebox.gc.GC;
 57 import jdk.test.whitebox.WhiteBox;
 58 import jdk.test.lib.Platform;
 59 import jdk.test.lib.Container;
 60 
 61 /**
 62  * The Class to be invoked by jtreg prior Test Suite execution to
 63  * collect information about VM.
 64  * Do not use any APIs that may not be available in all target VMs.
 65  * Properties set by this Class will be available in the @requires expressions.
 66  */
 67 public class VMProps implements Callable<Map<String, String>> {
 68     // value known to jtreg as an indicator of error state
 69     private static final String ERROR_STATE = "__ERROR__";
 70 
 71     private static final WhiteBox WB = WhiteBox.getWhiteBox();
 72 
 73     private static class SafeMap {
 74         private final Map<String, String> map = new HashMap<>();
 75 
 76         public void put(String key, Supplier<String> s) {
 77             String value;
 78             try {
 79                 value = s.get();
 80             } catch (Throwable t) {
 81                 System.err.println("failed to get value for " + key);
 82                 t.printStackTrace(System.err);
 83                 value = ERROR_STATE + t;
 84             }
 85             map.put(key, value);
 86         }
 87 
 88         public void putAll(Map<String, String> map) {
 89             map.entrySet().forEach(e -> put(e.getKey(), () -> e.getValue()));
 90         }
 91     }
 92 
 93     /**
 94      * Collects information about VM properties.
 95      * This method will be invoked by jtreg.
 96      *
 97      * @return Map of property-value pairs.
 98      */
 99     @Override
100     public Map<String, String> call() {
101         log("Entering call()");
102         SafeMap map = new SafeMap();
103         map.put("vm.flavor", this::vmFlavor);
104         map.put("vm.compMode", this::vmCompMode);
105         map.put("vm.bits", this::vmBits);
106         map.put("vm.flightRecorder", this::vmFlightRecorder);
107         map.put("vm.simpleArch", this::vmArch);
108         map.put("vm.debug", this::vmDebug);
109         map.put("vm.jvmci", this::vmJvmci);
110         map.put("vm.jvmci.enabled", this::vmJvmciEnabled);
111         map.put("vm.emulatedClient", this::vmEmulatedClient);
112         // vm.hasSA is "true" if the VM contains the serviceability agent
113         // and jhsdb.
114         map.put("vm.hasSA", this::vmHasSA);
115         // vm.hasJFR is "true" if JFR is included in the build of the VM and
116         // so tests can be executed.
117         map.put("vm.hasJFR", this::vmHasJFR);
118         map.put("vm.hasDTrace", this::vmHasDTrace);
119         map.put("vm.jvmti", this::vmHasJVMTI);
120         map.put("vm.cpu.features", this::cpuFeatures);
121         map.put("vm.pageSize", this::vmPageSize);
122         map.put("vm.rtm.cpu", this::vmRTMCPU);
123         map.put("vm.rtm.compiler", this::vmRTMCompiler);
124         // vm.cds is true if the VM is compiled with cds support.
125         map.put("vm.cds", this::vmCDS);
126         map.put("vm.cds.custom.loaders", this::vmCDSForCustomLoaders);
127         map.put("vm.cds.write.archived.java.heap", this::vmCDSCanWriteArchivedJavaHeap);
128         map.put("vm.continuations", this::vmContinuations);
129         // vm.graal.enabled is true if Graal is used as JIT
130         map.put("vm.graal.enabled", this::isGraalEnabled);
131         // jdk.hasLibgraal is true if the libgraal shared library file is present
132         map.put("jdk.hasLibgraal", this::hasLibgraal);
133         // vm.libgraal.enabled is true if libgraal is used as JIT
134         map.put("vm.libgraal.enabled", this::isLibgraalEnabled);
135         map.put("vm.compiler1.enabled", this::isCompiler1Enabled);
136         map.put("vm.compiler2.enabled", this::isCompiler2Enabled);
137         map.put("docker.support", this::dockerSupport);
138         map.put("vm.musl", this::isMusl);
139         map.put("release.implementor", this::implementor);
140         map.put("jdk.containerized", this::jdkContainerized);
141         map.put("vm.flagless", this::isFlagless);
142         map.put("jdk.foreign.linker", this::jdkForeignLinker);
143         map.putAll(xOptFlags()); // -Xmx4g -> @requires vm.opt.x.Xmx == "4g" )
144         vmGC(map); // vm.gc.X = true/false
145         vmGCforCDS(map); // may set vm.gc
146         vmOptFinalFlags(map);
147 
148         dump(map.map);
149         log("Leaving call()");
150         return map.map;
151     }
152 
153     /**
154      * Print a stack trace before returning error state;
155      * Used by the various helper functions which parse information from
156      * VM properties in the case where they don't find an expected property
157      * or a property doesn't conform to an expected format.
158      *
159      * @return {@link #ERROR_STATE}
160      */
161     private String errorWithMessage(String message) {
162         new Exception(message).printStackTrace();
163         return ERROR_STATE + message;
164     }
165 
166     /**
167      * @return vm.simpleArch value of "os.simpleArch" property of tested JDK.
168      */
169     protected String vmArch() {
170         String arch = System.getProperty("os.arch");
171         if (arch.equals("x86_64") || arch.equals("amd64")) {
172             return "x64";
173         } else if (arch.contains("86")) {
174             return "x86";
175         } else {
176             return arch;
177         }
178     }
179 
180     /**
181      * @return VM type value extracted from the "java.vm.name" property.
182      */
183     protected String vmFlavor() {
184         // E.g. "Java HotSpot(TM) 64-Bit Server VM"
185         String vmName = System.getProperty("java.vm.name");
186         if (vmName == null) {
187             return errorWithMessage("Can't get 'java.vm.name' property");
188         }
189 
190         Pattern startP = Pattern.compile(".* (\\S+) VM");
191         Matcher m = startP.matcher(vmName);
192         if (m.matches()) {
193             return m.group(1).toLowerCase();
194         }
195         return errorWithMessage("Can't get VM flavor from 'java.vm.name'");
196     }
197 
198     /**
199      * @return VM compilation mode extracted from the "java.vm.info" property.
200      */
201     protected String vmCompMode() {
202         // E.g. "mixed mode"
203         String vmInfo = System.getProperty("java.vm.info");
204         if (vmInfo == null) {
205             return errorWithMessage("Can't get 'java.vm.info' property");
206         }
207         vmInfo = vmInfo.toLowerCase();
208         if (vmInfo.contains("mixed mode")) {
209             return "Xmixed";
210         } else if (vmInfo.contains("compiled mode")) {
211             return "Xcomp";
212         } else if (vmInfo.contains("interpreted mode")) {
213             return "Xint";
214         } else {
215             return errorWithMessage("Can't get compilation mode from 'java.vm.info'");
216         }
217     }
218 
219     /**
220      * @return VM bitness, the value of the "sun.arch.data.model" property.
221      */
222     protected String vmBits() {
223         String dataModel = System.getProperty("sun.arch.data.model");
224         if (dataModel != null) {
225             return dataModel;
226         } else {
227             return errorWithMessage("Can't get 'sun.arch.data.model' property");
228         }
229     }
230 
231     /**
232      * @return "true" if Flight Recorder is enabled, "false" if is disabled.
233      */
234     protected String vmFlightRecorder() {
235         Boolean isFlightRecorder = WB.getBooleanVMFlag("FlightRecorder");
236         String startFROptions = WB.getStringVMFlag("StartFlightRecording");
237         if (isFlightRecorder != null && isFlightRecorder) {
238             return "true";
239         }
240         if (startFROptions != null && !startFROptions.isEmpty()) {
241             return "true";
242         }
243         return "false";
244     }
245 
246     /**
247      * @return debug level value extracted from the "jdk.debug" property.
248      */
249     protected String vmDebug() {
250         String debug = System.getProperty("jdk.debug");
251         if (debug != null) {
252             return "" + debug.contains("debug");
253         } else {
254             return errorWithMessage("Can't get 'jdk.debug' property");
255         }
256     }
257 
258     /**
259      * @return true if VM supports JVMCI and false otherwise
260      */
261     protected String vmJvmci() {
262         // builds with jvmci have this flag
263         if (WB.getBooleanVMFlag("EnableJVMCI") == null) {
264             return "false";
265         }
266 
267         // Not all GCs have full JVMCI support
268         if (!WB.isJVMCISupportedByGC()) {
269           return "false";
270         }
271 
272         // Interpreted mode cannot enable JVMCI
273         if (vmCompMode().equals("Xint")) {
274           return "false";
275         }
276 
277         return "true";
278     }
279 
280 
281     /**
282      * @return true if JVMCI is enabled
283      */
284     protected String vmJvmciEnabled() {
285         // builds with jvmci have this flag
286         if ("false".equals(vmJvmci())) {
287             return "false";
288         }
289 
290         return "" + Compiler.isJVMCIEnabled();
291     }
292 
293 
294     /**
295      * @return true if VM runs in emulated-client mode and false otherwise.
296      */
297     protected String vmEmulatedClient() {
298         String vmInfo = System.getProperty("java.vm.info");
299         if (vmInfo == null) {
300             return errorWithMessage("Can't get 'java.vm.info' property");
301         }
302         return "" + vmInfo.contains(" emulated-client");
303     }
304 
305     /**
306      * @return supported CPU features
307      */
308     protected String cpuFeatures() {
309         return CPUInfo.getFeatures().toString();
310     }
311 
312     /**
313      * For all existing GC sets vm.gc.X property.
314      * Example vm.gc.G1=true means:
315      *    VM supports G1
316      *    User either set G1 explicitely (-XX:+UseG1GC) or did not set any GC
317      *    G1 can be selected, i.e. it doesn't conflict with other VM flags
318      *
319      * @param map - property-value pairs
320      */
321     protected void vmGC(SafeMap map) {
322         var isJVMCIEnabled = Compiler.isJVMCIEnabled();
323         Predicate<GC> vmGCProperty = (GC gc) -> (gc.isSupported()
324                                         && (!isJVMCIEnabled || gc.isSupportedByJVMCICompiler())
325                                         && (gc.isSelected() || GC.isSelectedErgonomically()));
326         for (GC gc: GC.values()) {
327             map.put("vm.gc." + gc.name(), () -> "" + vmGCProperty.test(gc));
328         }
329 
330         // Special handling for ZGC modes
331         var vmGCZ = vmGCProperty.test(GC.Z);
332         var genZ = WB.getBooleanVMFlag("ZGenerational");
333         var genZIsDefault = WB.isDefaultVMFlag("ZGenerational");
334         // vm.gc.ZGenerational=true means:
335         //    vm.gc.Z is true and ZGenerational is either explicitly true, or default
336         map.put("vm.gc.ZGenerational", () -> "" + (vmGCZ && (genZ || genZIsDefault)));
337         // vm.gc.ZSinglegen=true means:
338         //    vm.gc.Z is true and ZGenerational is either explicitly false, or default
339         map.put("vm.gc.ZSinglegen", () -> "" + (vmGCZ && (!genZ || genZIsDefault)));
340     }
341 
342     /**
343      * "jtreg -vmoptions:-Dtest.cds.runtime.options=..." can be used to specify
344      * the GC type to be used when running with a CDS archive. Set "vm.gc" accordingly,
345      * so that tests that need to explicitly choose the GC type can be excluded
346      * with "@requires vm.gc == null".
347      *
348      * @param map - property-value pairs
349      */
350     protected void vmGCforCDS(SafeMap map) {
351         if (!GC.isSelectedErgonomically()) {
352             // The GC has been explicitly specified on the command line, so
353             // jtreg will set the "vm.gc" property. Let's not interfere with it.
354             return;
355         }
356 
357         String GC_PREFIX  = "-XX:+Use";
358         String GC_SUFFIX  = "GC";
359         String jtropts = System.getProperty("test.cds.runtime.options");
360         if (jtropts != null) {
361             for (String opt : jtropts.split(",")) {
362                 if (opt.startsWith(GC_PREFIX) && opt.endsWith(GC_SUFFIX)) {
363                     String gc = opt.substring(GC_PREFIX.length(), opt.length() - GC_SUFFIX.length());
364                     map.put("vm.gc", () -> gc);
365                 }
366             }
367         }
368     }
369 
370     /**
371      * Selected final flag.
372      *
373      * @param map - property-value pairs
374      * @param flagName - flag name
375      */
376     private void vmOptFinalFlag(SafeMap map, String flagName) {
377         map.put("vm.opt.final." + flagName,
378                 () -> String.valueOf(WB.getBooleanVMFlag(flagName)));
379     }
380 
381     /**
382      * Selected sets of final flags.
383      *
384      * @param map - property-value pairs
385      */
386     protected void vmOptFinalFlags(SafeMap map) {
387         vmOptFinalFlag(map, "ClassUnloading");
388         vmOptFinalFlag(map, "ClassUnloadingWithConcurrentMark");
389         vmOptFinalFlag(map, "CriticalJNINatives");
390         vmOptFinalFlag(map, "EnableJVMCI");
391         vmOptFinalFlag(map, "EliminateAllocations");
392         vmOptFinalFlag(map, "TieredCompilation");
393         vmOptFinalFlag(map, "UseCompressedOops");
394         vmOptFinalFlag(map, "UseVectorizedMismatchIntrinsic");
395         vmOptFinalFlag(map, "UseVtableBasedCHA");
396         vmOptFinalFlag(map, "ZGenerational");
397     }
398 
399     /**
400      * @return "true" if VM has a serviceability agent.
401      */
402     protected String vmHasSA() {
403         return "" + Platform.hasSA();
404     }
405 
406     /**
407      * @return "true" if the VM is compiled with Java Flight Recorder (JFR)
408      * support.
409      */
410     protected String vmHasJFR() {
411         return "" + WB.isJFRIncluded();
412     }
413 
414     /**
415      * @return "true" if the VM is compiled with JVMTI
416      */
417     protected String vmHasJVMTI() {
418         return "" + WB.isJVMTIIncluded();
419     }
420 
421     /**
422      * @return "true" if the VM is compiled with DTrace
423      */
424     protected String vmHasDTrace() {
425         return "" + WB.isDTraceIncluded();
426     }
427 
428     /**
429      * @return true if compiler in use supports RTM and false otherwise.
430      */
431     protected String vmRTMCompiler() {
432         boolean isRTMCompiler = false;
433 
434         if (Compiler.isC2Enabled() &&
435             (Platform.isX86() || Platform.isX64() || Platform.isPPC())) {
436             isRTMCompiler = true;
437         }
438         return "" + isRTMCompiler;
439     }
440 
441     /**
442      * @return true if VM runs RTM supported CPU and false otherwise.
443      */
444     protected String vmRTMCPU() {
445         return "" + CPUInfo.hasFeature("rtm");
446     }
447 
448     /**
449      * Check for CDS support.
450      *
451      * @return true if CDS is supported by the VM to be tested.
452      */
453     protected String vmCDS() {
454         return "" + WB.isCDSIncluded();
455     }
456 
457     /**
458      * Check for CDS support for custom loaders.
459      *
460      * @return true if CDS provides support for customer loader in the VM to be tested.
461      */
462     protected String vmCDSForCustomLoaders() {
463         return "" + ("true".equals(vmCDS()) && Platform.areCustomLoadersSupportedForCDS());
464     }
465 
466     /**
467      * @return true if this VM can write Java heap objects into the CDS archive
468      */
469     protected String vmCDSCanWriteArchivedJavaHeap() {
470         return "" + ("true".equals(vmCDS()) && WB.canWriteJavaHeapArchive());
471     }
472 
473     /**
474      * @return "true" if this VM supports continuations.
475      */
476     protected String vmContinuations() {
477         if (WB.getBooleanVMFlag("VMContinuations")) {
478             return "true";
479         } else {
480             return "false";
481         }
482     }
483 
484     /**
485      * @return System page size in bytes.
486      */
487     protected String vmPageSize() {
488         return "" + WB.getVMPageSize();
489     }
490 
491     /**
492      * Check if Graal is used as JIT compiler.
493      *
494      * @return true if Graal is used as JIT compiler.
495      */
496     protected String isGraalEnabled() {
497         return "" + Compiler.isGraalEnabled();
498     }
499 
500     /**
501      * Check if the libgraal shared library file is present.
502      *
503      * @return true if the libgraal shared library file is present.
504      */
505     protected String hasLibgraal() {
506         return "" + WB.hasLibgraal();
507     }
508 
509     /**
510      * Check if libgraal is used as JIT compiler.
511      *
512      * @return true if libgraal is used as JIT compiler.
513      */
514     protected String isLibgraalEnabled() {
515         return "" + Compiler.isLibgraalEnabled();
516     }
517 
518     /**
519      * Check if Compiler1 is present.
520      *
521      * @return true if Compiler1 is used as JIT compiler, either alone or as part of the tiered system.
522      */
523     protected String isCompiler1Enabled() {
524         return "" + Compiler.isC1Enabled();
525     }
526 
527     /**
528      * Check if Compiler2 is present.
529      *
530      * @return true if Compiler2 is used as JIT compiler, either alone or as part of the tiered system.
531      */
532     protected String isCompiler2Enabled() {
533         return "" + Compiler.isC2Enabled();
534     }
535 
536     /**
537      * A simple check for docker support
538      *
539      * @return true if docker is supported in a given environment
540      */
541     protected String dockerSupport() {
542         log("Entering dockerSupport()");
543 
544         boolean isSupported = false;
545         if (Platform.isLinux()) {
546            // currently docker testing is only supported for Linux,
547            // on certain platforms
548 
549            String arch = System.getProperty("os.arch");
550 
551            if (Platform.isX64()) {
552               isSupported = true;
553            } else if (Platform.isAArch64()) {
554               isSupported = true;
555            } else if (Platform.isS390x()) {
556               isSupported = true;
557            } else if (arch.equals("ppc64le")) {
558               isSupported = true;
559            }
560         }
561 
562         log("dockerSupport(): platform check: isSupported = " + isSupported);
563 
564         if (isSupported) {
565            try {
566               isSupported = checkDockerSupport();
567            } catch (Exception e) {
568               isSupported = false;
569            }
570          }
571 
572         log("dockerSupport(): returning isSupported = " + isSupported);
573         return "" + isSupported;
574     }
575 
576     // Configures process builder to redirect process stdout and stderr to a file.
577     // Returns file names for stdout and stderr.
578     private Map<String, String> redirectOutputToLogFile(String msg, ProcessBuilder pb, String fileNameBase) {
579         Map<String, String> result = new HashMap<>();
580         String timeStamp = Instant.now().toString().replace(":", "-").replace(".", "-");
581 
582         String stdoutFileName = String.format("./%s-stdout--%s.log", fileNameBase, timeStamp);
583         pb.redirectOutput(new File(stdoutFileName));
584         log(msg + ": child process stdout redirected to " + stdoutFileName);
585         result.put("stdout", stdoutFileName);
586 
587         String stderrFileName = String.format("./%s-stderr--%s.log", fileNameBase, timeStamp);
588         pb.redirectError(new File(stderrFileName));
589         log(msg + ": child process stderr redirected to " + stderrFileName);
590         result.put("stderr", stderrFileName);
591 
592         return result;
593     }
594 
595     private void printLogfileContent(Map<String, String> logFileNames) {
596         logFileNames.entrySet().stream()
597             .forEach(entry ->
598                 {
599                     log("------------- " + entry.getKey());
600                     try {
601                         Files.lines(Path.of(entry.getValue()))
602                             .forEach(line -> log(line));
603                     } catch (IOException ie) {
604                         log("Exception while reading file: " + ie);
605                     }
606                     log("-------------");
607                 });
608     }
609 
610     private boolean checkDockerSupport() throws IOException, InterruptedException {
611         log("checkDockerSupport(): entering");
612         ProcessBuilder pb = new ProcessBuilder("which", Container.ENGINE_COMMAND);
613         Map<String, String> logFileNames =
614             redirectOutputToLogFile("checkDockerSupport(): which " + Container.ENGINE_COMMAND,
615                                                       pb, "which-container");
616         Process p = pb.start();
617         p.waitFor(10, TimeUnit.SECONDS);
618         int exitValue = p.exitValue();
619 
620         log(String.format("checkDockerSupport(): exitValue = %s, pid = %s", exitValue, p.pid()));
621         if (exitValue != 0) {
622             printLogfileContent(logFileNames);
623         }
624 
625         return (exitValue == 0);
626     }
627 
628     /**
629      * Checks musl libc.
630      *
631      * @return true if musl libc is used.
632      */
633     protected String isMusl() {
634         return Boolean.toString(WB.getLibcName().contains("musl"));
635     }
636 
637     private String implementor() {
638         try (InputStream in = new BufferedInputStream(new FileInputStream(
639                 System.getProperty("java.home") + "/release"))) {
640             Properties properties = new Properties();
641             properties.load(in);
642             String implementorProperty = properties.getProperty("IMPLEMENTOR");
643             if (implementorProperty != null) {
644                 return implementorProperty.replace("\"", "");
645             }
646             return errorWithMessage("Can't get 'IMPLEMENTOR' property from 'release' file");
647         } catch (IOException e) {
648             e.printStackTrace();
649             return errorWithMessage("Failed to read 'release' file " + e);
650         }
651     }
652 
653     private String jdkContainerized() {
654         String isEnabled = System.getenv("TEST_JDK_CONTAINERIZED");
655         return "" + "true".equalsIgnoreCase(isEnabled);
656     }
657 
658     /**
659      * Checks if we are in <i>almost</i> out-of-box configuration, i.e. the flags
660      * which JVM is started with don't affect its behavior "significantly".
661      * {@code TEST_VM_FLAGLESS} enviroment variable can be used to force this
662      * method to return true and allow any flags.
663      *
664      * @return true if there are no JVM flags
665      */
666     private String isFlagless() {
667         boolean result = true;
668         if (System.getenv("TEST_VM_FLAGLESS") != null) {
669             return "" + result;
670         }
671 
672         List<String> allFlags = allFlags().toList();
673 
674         // check -XX flags
675         var ignoredXXFlags = Set.of(
676                 // added by run-test framework
677                 "MaxRAMPercentage",
678                 // added by test environment
679                 "CreateCoredumpOnCrash"
680         );
681         result &= allFlags.stream()
682                           .filter(s -> s.startsWith("-XX:"))
683                           // map to names:
684                               // remove -XX:
685                               .map(s -> s.substring(4))
686                               // remove +/- from bool flags
687                               .map(s -> s.charAt(0) == '+' || s.charAt(0) == '-' ? s.substring(1) : s)
688                               // remove =.* from others
689                               .map(s -> s.contains("=") ? s.substring(0, s.indexOf('=')) : s)
690                           // skip known-to-be-there flags
691                           .filter(s -> !ignoredXXFlags.contains(s))
692                           .findAny()
693                           .isEmpty();
694 
695         // check -X flags
696         var ignoredXFlags = Set.of(
697                 // default, yet still seen to be explicitly set
698                 "mixed",
699                 // -XmxmNNNm added by run-test framework for non-hotspot tests
700                 "mx"
701         );
702         result &= allFlags.stream()
703                           .filter(s -> s.startsWith("-X") && !s.startsWith("-XX:"))
704                           // map to names:
705                           // remove -X
706                           .map(s -> s.substring(2))
707                           // remove :.* from flags with values
708                           .map(s -> s.contains(":") ? s.substring(0, s.indexOf(':')) : s)
709                           // remove size like 4G, 768m which might be set for non-hotspot tests
710                           .map(s -> s.replaceAll("(\\d+)[mMgGkK]", ""))
711                           // skip known-to-be-there flags
712                           .filter(s -> !ignoredXFlags.contains(s))
713                           .findAny()
714                           .isEmpty();
715 
716         return "" + result;
717     }
718 
719     private Stream<String> allFlags() {
720         return Stream.of((System.getProperty("test.vm.opts", "") + " " + System.getProperty("test.java.opts", "")).trim().split("\\s+"));
721     }
722 
723     /**
724      * Parses extra options, options that start with -X excluding the
725      * bare -X option (as it is not considered an extra option).
726      * Ignores extra options not starting with -X
727      *
728      * This could be improved to handle extra options not starting
729      * with -X as well as "standard" options.
730      */
731     private Map<String, String> xOptFlags() {
732         return allFlags()
733             .filter(s -> s.startsWith("-X") && !s.startsWith("-XX:") && !s.equals("-X"))
734             .map(s -> s.replaceFirst("-", ""))
735             .map(flag -> flag.splitWithDelimiters("[:0123456789]", 2))
736             .collect(Collectors.toMap(a -> "vm.opt.x." + a[0],
737                                       a -> (a.length == 1)
738                                       ? "true" // -Xnoclassgc
739                                       : (a[1].equals(":")
740                                          ? a[2]            // ["-XshowSettings", ":", "system"]
741                                          : a[1] + a[2]))); // ["-Xmx", "4", "g"]
742     }
743 
744     /*
745      * A string indicating the foreign linker that is currently being used. See jdk.internal.foreign.CABI
746      * for valid values.
747      *
748      * "FALLBACK" and "UNSUPPORTED" are special values. The former indicates the fallback linker is
749      * being used. The latter indicates an unsupported platform.
750      */
751     private String jdkForeignLinker() {
752         return String.valueOf(CABI.current());
753     }
754 
755     /**
756      * Dumps the map to the file if the file name is given as the property.
757      * This functionality could be helpful to know context in the real
758      * execution.
759      *
760      * @param map
761      */
762     protected static void dump(Map<String, String> map) {
763         String dumpFileName = System.getProperty("vmprops.dump");
764         if (dumpFileName == null) {
765             return;
766         }
767         List<String> lines = new ArrayList<>();
768         map.forEach((k, v) -> lines.add(k + ":" + v));
769         Collections.sort(lines);
770         try {
771             Files.write(Paths.get(dumpFileName), lines,
772                     StandardOpenOption.APPEND, StandardOpenOption.CREATE);
773         } catch (IOException e) {
774             throw new RuntimeException("Failed to dump properties into '"
775                     + dumpFileName + "'", e);
776         }
777     }
778 
779     /**
780      * Log diagnostic message.
781      *
782      * @param msg
783      */
784     protected static void log(String msg) {
785         // Always log to a file.
786         logToFile(msg);
787 
788         // Also log to stderr; guarded by property to avoid excessive verbosity.
789         // By jtreg design stderr produced here will be visible
790         // in the output of a parent process. Note: stdout should not be used
791         // for logging as jtreg parses that output directly and only echoes it
792         // in the event of a failure.
793         if (Boolean.getBoolean("jtreg.log.vmprops")) {
794             System.err.println("VMProps: " + msg);
795         }
796     }
797 
798     /**
799      * Log diagnostic message to a file.
800      *
801      * @param msg
802      */
803     protected static void logToFile(String msg) {
804         String fileName = "./vmprops.log";
805         try {
806             Files.writeString(Paths.get(fileName), msg + "\n", Charset.forName("ISO-8859-1"),
807                     StandardOpenOption.APPEND, StandardOpenOption.CREATE);
808         } catch (IOException e) {
809             throw new RuntimeException("Failed to log into '" + fileName + "'", e);
810         }
811     }
812 
813     /**
814      * This method is for the testing purpose only.
815      *
816      * @param args
817      */
818     public static void main(String args[]) {
819         Map<String, String> map = new VMProps().call();
820         map.forEach((k, v) -> System.out.println(k + ": '" + v + "'"));
821     }
822 }