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