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