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