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, "UseCompressedOops");
393         vmOptFinalFlag(map, "UseVectorizedMismatchIntrinsic");
394         vmOptFinalFlag(map, "UseVtableBasedCHA");
395         vmOptFinalFlag(map, "ZGenerational");
396     }
397 
398     /**
399      * @return "true" if VM has a serviceability agent.
400      */
401     protected String vmHasSA() {
402         return "" + Platform.hasSA();
403     }
404 
405     /**
406      * @return "true" if the VM is compiled with Java Flight Recorder (JFR)
407      * support.
408      */
409     protected String vmHasJFR() {
410         return "" + WB.isJFRIncluded();
411     }
412 
413     /**
414      * @return "true" if the VM is compiled with JVMTI
415      */
416     protected String vmHasJVMTI() {
417         return "" + WB.isJVMTIIncluded();
418     }
419 
420     /**
421      * @return "true" if the VM is compiled with DTrace
422      */
423     protected String vmHasDTrace() {
424         return "" + WB.isDTraceIncluded();
425     }
426 
427     /**
428      * @return true if compiler in use supports RTM and false otherwise.
429      */
430     protected String vmRTMCompiler() {
431         boolean isRTMCompiler = false;
432 
433         if (Compiler.isC2Enabled() &&
434             (Platform.isX86() || Platform.isX64() || Platform.isPPC())) {
435             isRTMCompiler = true;
436         }
437         return "" + isRTMCompiler;
438     }
439 
440     /**
441      * @return true if VM runs RTM supported CPU and false otherwise.
442      */
443     protected String vmRTMCPU() {
444         return "" + CPUInfo.hasFeature("rtm");
445     }
446 
447     /**
448      * Check for CDS support.
449      *
450      * @return true if CDS is supported by the VM to be tested.
451      */
452     protected String vmCDS() {
453         return "" + WB.isCDSIncluded();
454     }
455 
456     /**
457      * Check for CDS support for custom loaders.
458      *
459      * @return true if CDS provides support for customer loader in the VM to be tested.
460      */
461     protected String vmCDSForCustomLoaders() {
462         return "" + ("true".equals(vmCDS()) && Platform.areCustomLoadersSupportedForCDS());
463     }
464 
465     /**
466      * @return true if this VM can write Java heap objects into the CDS archive
467      */
468     protected String vmCDSCanWriteArchivedJavaHeap() {
469         return "" + ("true".equals(vmCDS()) && WB.canWriteJavaHeapArchive());
470     }
471 
472     /**
473      * @return "true" if this VM supports continuations.
474      */
475     protected String vmContinuations() {
476         if (WB.getBooleanVMFlag("VMContinuations")) {
477             return "true";
478         } else {
479             return "false";
480         }
481     }
482 
483     /**
484      * @return System page size in bytes.
485      */
486     protected String vmPageSize() {
487         return "" + WB.getVMPageSize();
488     }
489 
490     /**
491      * Check if Graal is used as JIT compiler.
492      *
493      * @return true if Graal is used as JIT compiler.
494      */
495     protected String isGraalEnabled() {
496         return "" + Compiler.isGraalEnabled();
497     }
498 
499     /**
500      * Check if the libgraal shared library file is present.
501      *
502      * @return true if the libgraal shared library file is present.
503      */
504     protected String hasLibgraal() {
505         return "" + WB.hasLibgraal();
506     }
507 
508     /**
509      * Check if libgraal is used as JIT compiler.
510      *
511      * @return true if libgraal is used as JIT compiler.
512      */
513     protected String isLibgraalEnabled() {
514         return "" + Compiler.isLibgraalEnabled();
515     }
516 
517     /**
518      * Check if Compiler1 is present.
519      *
520      * @return true if Compiler1 is used as JIT compiler, either alone or as part of the tiered system.
521      */
522     protected String isCompiler1Enabled() {
523         return "" + Compiler.isC1Enabled();
524     }
525 
526     /**
527      * Check if Compiler2 is present.
528      *
529      * @return true if Compiler2 is used as JIT compiler, either alone or as part of the tiered system.
530      */
531     protected String isCompiler2Enabled() {
532         return "" + Compiler.isC2Enabled();
533     }
534 
535     /**
536      * A simple check for docker support
537      *
538      * @return true if docker is supported in a given environment
539      */
540     protected String dockerSupport() {
541         log("Entering dockerSupport()");
542 
543         boolean isSupported = false;
544         if (Platform.isLinux()) {
545            // currently docker testing is only supported for Linux,
546            // on certain platforms
547 
548            String arch = System.getProperty("os.arch");
549 
550            if (Platform.isX64()) {
551               isSupported = true;
552            } else if (Platform.isAArch64()) {
553               isSupported = true;
554            } else if (Platform.isS390x()) {
555               isSupported = true;
556            } else if (arch.equals("ppc64le")) {
557               isSupported = true;
558            }
559         }
560 
561         log("dockerSupport(): platform check: isSupported = " + isSupported);
562 
563         if (isSupported) {
564            try {
565               isSupported = checkDockerSupport();
566            } catch (Exception e) {
567               isSupported = false;
568            }
569          }
570 
571         log("dockerSupport(): returning isSupported = " + isSupported);
572         return "" + isSupported;
573     }
574 
575     // Configures process builder to redirect process stdout and stderr to a file.
576     // Returns file names for stdout and stderr.
577     private Map<String, String> redirectOutputToLogFile(String msg, ProcessBuilder pb, String fileNameBase) {
578         Map<String, String> result = new HashMap<>();
579         String timeStamp = Instant.now().toString().replace(":", "-").replace(".", "-");
580 
581         String stdoutFileName = String.format("./%s-stdout--%s.log", fileNameBase, timeStamp);
582         pb.redirectOutput(new File(stdoutFileName));
583         log(msg + ": child process stdout redirected to " + stdoutFileName);
584         result.put("stdout", stdoutFileName);
585 
586         String stderrFileName = String.format("./%s-stderr--%s.log", fileNameBase, timeStamp);
587         pb.redirectError(new File(stderrFileName));
588         log(msg + ": child process stderr redirected to " + stderrFileName);
589         result.put("stderr", stderrFileName);
590 
591         return result;
592     }
593 
594     private void printLogfileContent(Map<String, String> logFileNames) {
595         logFileNames.entrySet().stream()
596             .forEach(entry ->
597                 {
598                     log("------------- " + entry.getKey());
599                     try {
600                         Files.lines(Path.of(entry.getValue()))
601                             .forEach(line -> log(line));
602                     } catch (IOException ie) {
603                         log("Exception while reading file: " + ie);
604                     }
605                     log("-------------");
606                 });
607     }
608 
609     private boolean checkDockerSupport() throws IOException, InterruptedException {
610         log("checkDockerSupport(): entering");
611         ProcessBuilder pb = new ProcessBuilder("which", Container.ENGINE_COMMAND);
612         Map<String, String> logFileNames =
613             redirectOutputToLogFile("checkDockerSupport(): which " + Container.ENGINE_COMMAND,
614                                                       pb, "which-container");
615         Process p = pb.start();
616         p.waitFor(10, TimeUnit.SECONDS);
617         int exitValue = p.exitValue();
618 
619         log(String.format("checkDockerSupport(): exitValue = %s, pid = %s", exitValue, p.pid()));
620         if (exitValue != 0) {
621             printLogfileContent(logFileNames);
622         }
623 
624         return (exitValue == 0);
625     }
626 
627     /**
628      * Checks musl libc.
629      *
630      * @return true if musl libc is used.
631      */
632     protected String isMusl() {
633         return Boolean.toString(WB.getLibcName().contains("musl"));
634     }
635 
636     private String implementor() {
637         try (InputStream in = new BufferedInputStream(new FileInputStream(
638                 System.getProperty("java.home") + "/release"))) {
639             Properties properties = new Properties();
640             properties.load(in);
641             String implementorProperty = properties.getProperty("IMPLEMENTOR");
642             if (implementorProperty != null) {
643                 return implementorProperty.replace("\"", "");
644             }
645             return errorWithMessage("Can't get 'IMPLEMENTOR' property from 'release' file");
646         } catch (IOException e) {
647             e.printStackTrace();
648             return errorWithMessage("Failed to read 'release' file " + e);
649         }
650     }
651 
652     private String jdkContainerized() {
653         String isEnabled = System.getenv("TEST_JDK_CONTAINERIZED");
654         return "" + "true".equalsIgnoreCase(isEnabled);
655     }
656 
657     /**
658      * Checks if we are in <i>almost</i> out-of-box configuration, i.e. the flags
659      * which JVM is started with don't affect its behavior "significantly".
660      * {@code TEST_VM_FLAGLESS} enviroment variable can be used to force this
661      * method to return true and allow any flags.
662      *
663      * @return true if there are no JVM flags
664      */
665     private String isFlagless() {
666         boolean result = true;
667         if (System.getenv("TEST_VM_FLAGLESS") != null) {
668             return "" + result;
669         }
670 
671         List<String> allFlags = allFlags().toList();
672 
673         // check -XX flags
674         var ignoredXXFlags = Set.of(
675                 // added by run-test framework
676                 "MaxRAMPercentage",
677                 // added by test environment
678                 "CreateCoredumpOnCrash"
679         );
680         result &= allFlags.stream()
681                           .filter(s -> s.startsWith("-XX:"))
682                           // map to names:
683                               // remove -XX:
684                               .map(s -> s.substring(4))
685                               // remove +/- from bool flags
686                               .map(s -> s.charAt(0) == '+' || s.charAt(0) == '-' ? s.substring(1) : s)
687                               // remove =.* from others
688                               .map(s -> s.contains("=") ? s.substring(0, s.indexOf('=')) : s)
689                           // skip known-to-be-there flags
690                           .filter(s -> !ignoredXXFlags.contains(s))
691                           .findAny()
692                           .isEmpty();
693 
694         // check -X flags
695         var ignoredXFlags = Set.of(
696                 // default, yet still seen to be explicitly set
697                 "mixed",
698                 // -XmxmNNNm added by run-test framework for non-hotspot tests
699                 "mx"
700         );
701         result &= allFlags.stream()
702                           .filter(s -> s.startsWith("-X") && !s.startsWith("-XX:"))
703                           // map to names:
704                           // remove -X
705                           .map(s -> s.substring(2))
706                           // remove :.* from flags with values
707                           .map(s -> s.contains(":") ? s.substring(0, s.indexOf(':')) : s)
708                           // remove size like 4G, 768m which might be set for non-hotspot tests
709                           .map(s -> s.replaceAll("(\\d+)[mMgGkK]", ""))
710                           // skip known-to-be-there flags
711                           .filter(s -> !ignoredXFlags.contains(s))
712                           .findAny()
713                           .isEmpty();
714 
715         return "" + result;
716     }
717 
718     private Stream<String> allFlags() {
719         return Stream.of((System.getProperty("test.vm.opts", "") + " " + System.getProperty("test.java.opts", "")).trim().split("\\s+"));
720     }
721 
722     /**
723      * Parses extra options, options that start with -X excluding the
724      * bare -X option (as it is not considered an extra option).
725      * Ignores extra options not starting with -X
726      *
727      * This could be improved to handle extra options not starting
728      * with -X as well as "standard" options.
729      */
730     private Map<String, String> xOptFlags() {
731         return allFlags()
732             .filter(s -> s.startsWith("-X") && !s.startsWith("-XX:") && !s.equals("-X"))
733             .map(s -> s.replaceFirst("-", ""))
734             .map(flag -> flag.splitWithDelimiters("[:0123456789]", 2))
735             .collect(Collectors.toMap(a -> "vm.opt.x." + a[0],
736                                       a -> (a.length == 1)
737                                       ? "true" // -Xnoclassgc
738                                       : (a[1].equals(":")
739                                          ? a[2]            // ["-XshowSettings", ":", "system"]
740                                          : a[1] + a[2]))); // ["-Xmx", "4", "g"]
741     }
742 
743     /*
744      * A string indicating the foreign linker that is currently being used. See jdk.internal.foreign.CABI
745      * for valid values.
746      *
747      * "FALLBACK" and "UNSUPPORTED" are special values. The former indicates the fallback linker is
748      * being used. The latter indicates an unsupported platform.
749      */
750     private String jdkForeignLinker() {
751         return String.valueOf(CABI.current());
752     }
753 
754     /**
755      * Dumps the map to the file if the file name is given as the property.
756      * This functionality could be helpful to know context in the real
757      * execution.
758      *
759      * @param map
760      */
761     protected static void dump(Map<String, String> map) {
762         String dumpFileName = System.getProperty("vmprops.dump");
763         if (dumpFileName == null) {
764             return;
765         }
766         List<String> lines = new ArrayList<>();
767         map.forEach((k, v) -> lines.add(k + ":" + v));
768         Collections.sort(lines);
769         try {
770             Files.write(Paths.get(dumpFileName), lines,
771                     StandardOpenOption.APPEND, StandardOpenOption.CREATE);
772         } catch (IOException e) {
773             throw new RuntimeException("Failed to dump properties into '"
774                     + dumpFileName + "'", e);
775         }
776     }
777 
778     /**
779      * Log diagnostic message.
780      *
781      * @param msg
782      */
783     protected static void log(String msg) {
784         // Always log to a file.
785         logToFile(msg);
786 
787         // Also log to stderr; guarded by property to avoid excessive verbosity.
788         // By jtreg design stderr produced here will be visible
789         // in the output of a parent process. Note: stdout should not be used
790         // for logging as jtreg parses that output directly and only echoes it
791         // in the event of a failure.
792         if (Boolean.getBoolean("jtreg.log.vmprops")) {
793             System.err.println("VMProps: " + msg);
794         }
795     }
796 
797     /**
798      * Log diagnostic message to a file.
799      *
800      * @param msg
801      */
802     protected static void logToFile(String msg) {
803         String fileName = "./vmprops.log";
804         try {
805             Files.writeString(Paths.get(fileName), msg + "\n", Charset.forName("ISO-8859-1"),
806                     StandardOpenOption.APPEND, StandardOpenOption.CREATE);
807         } catch (IOException e) {
808             throw new RuntimeException("Failed to log into '" + fileName + "'", e);
809         }
810     }
811 
812     /**
813      * This method is for the testing purpose only.
814      *
815      * @param args
816      */
817     public static void main(String args[]) {
818         Map<String, String> map = new VMProps().call();
819         map.forEach((k, v) -> System.out.println(k + ": '" + v + "'"));
820     }
821 }