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