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