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, "UnlockExperimentalVMOptions");
382         vmOptFinalFlag(map, "UseCompressedOops");
383         vmOptFinalFlag(map, "UseLargePages");
384         vmOptFinalFlag(map, "UseTransparentHugePages");
385         vmOptFinalFlag(map, "UseVectorizedMismatchIntrinsic");
386     }
387 
388     /**
389      * @return "true" if VM has a serviceability agent.
390      */
391     protected String vmHasSA() {
392         return "" + Platform.hasSA();
393     }
394 
395     /**
396      * @return "true" if the VM is compiled with Java Flight Recorder (JFR)
397      * support.
398      */
399     protected String vmHasJFR() {
400         return "" + WB.isJFRIncluded();
401     }
402 
403     /**
404      * @return "true" if the VM is compiled with JVMTI
405      */
406     protected String vmHasJVMTI() {
407         return "" + WB.isJVMTIIncluded();
408     }
409 
410     /**
411      * @return "true" if the VM is compiled with DTrace
412      */
413     protected String vmHasDTrace() {
414         return "" + WB.isDTraceIncluded();
415     }
416 
417     /**
418      * @return "true" if compiler in use supports RTM and "false" otherwise.
419      * Note: Lightweight locking does not support RTM (for now).
420      */
421     protected String vmRTMCompiler() {
422         boolean isRTMCompiler = false;
423 
424         if (Compiler.isC2Enabled() &&
425             (Platform.isX86() || Platform.isX64() || Platform.isPPC()) &&
426             is_LM_LIGHTWEIGHT().equals("false")) {
427             isRTMCompiler = true;
428         }
429         return "" + isRTMCompiler;
430     }
431 
432     /**
433      * @return true if VM runs RTM supported CPU and false otherwise.
434      */
435     protected String vmRTMCPU() {
436         return "" + CPUInfo.hasFeature("rtm");
437     }
438 
439     /**
440      * Check for CDS support.
441      *
442      * @return true if CDS is supported by the VM to be tested.
443      */
444     protected String vmCDS() {
445         return "" + WB.isCDSIncluded();
446     }
447 
448     /**
449      * Check for CDS support for custom loaders.
450      *
451      * @return true if CDS provides support for customer loader in the VM to be tested.
452      */
453     protected String vmCDSForCustomLoaders() {
454         return "" + ("true".equals(vmCDS()) && Platform.areCustomLoadersSupportedForCDS());
455     }
456 
457     /**
458      * @return true if it's possible for "java -Xshare:dump" to write Java heap objects
459      *         with the current set of jtreg VM options. For example, false will be returned
460      *         if -XX:-UseCompressedClassPointers is specified,
461      */
462     protected String vmCDSCanWriteArchivedJavaHeap() {
463         return "" + ("true".equals(vmCDS()) && WB.canWriteJavaHeapArchive()
464                      && isCDSRuntimeOptionsCompatible());
465     }
466 
467     /**
468      * @return true if this VM can support the -XX:AOTClassLinking option
469      */
470     protected String vmCDSSupportsAOTClassLinking() {
471       // Currently, the VM supports AOTClassLinking as long as it's able to write archived java heap.
472       return vmCDSCanWriteArchivedJavaHeap();
473     }
474 
475     /**
476      * @return true if the VM options specified via the "test.cds.runtime.options"
477      * property is compatible with writing Java heap objects into the CDS archive
478      */
479     protected boolean isCDSRuntimeOptionsCompatible() {
480         String jtropts = System.getProperty("test.cds.runtime.options");
481         if (jtropts == null) {
482             return true;
483         }
484         String CCP_DISABLED = "-XX:-UseCompressedClassPointers";
485         String G1GC_ENABLED = "-XX:+UseG1GC";
486         String PARALLELGC_ENABLED = "-XX:+UseParallelGC";
487         String SERIALGC_ENABLED = "-XX:+UseSerialGC";
488         for (String opt : jtropts.split(",")) {
489             if (opt.equals(CCP_DISABLED)) {
490                 return false;
491             }
492             if (opt.startsWith(GC_PREFIX) && opt.endsWith(GC_SUFFIX) &&
493                 !opt.equals(G1GC_ENABLED) && !opt.equals(PARALLELGC_ENABLED) && !opt.equals(SERIALGC_ENABLED)) {
494                 return false;
495             }
496         }
497         return true;
498     }
499 
500     /**
501      * @return "true" if this VM supports continuations.
502      */
503     protected String vmContinuations() {
504         if (WB.getBooleanVMFlag("VMContinuations")) {
505             return "true";
506         } else {
507             return "false";
508         }
509     }
510 
511     /**
512      * @return System page size in bytes.
513      */
514     protected String vmPageSize() {
515         return "" + WB.getVMPageSize();
516     }
517 
518     /**
519      * @return LockingMode.
520      */
521     protected String vmLockingMode() {
522         return "" + WB.getIntVMFlag("LockingMode");
523     }
524 
525     /**
526      * @return "true" if LockingMode == 0 (LM_MONITOR)
527      */
528     protected String is_LM_MONITOR() {
529         return "" + vmLockingMode().equals("0");
530     }
531 
532     /**
533      * @return "true" if LockingMode == 1 (LM_LEGACY)
534      */
535     protected String is_LM_LEGACY() {
536         return "" + vmLockingMode().equals("1");
537     }
538 
539     /**
540      * @return "true" if LockingMode == 2 (LM_LIGHTWEIGHT)
541      */
542     protected String is_LM_LIGHTWEIGHT() {
543         return "" + vmLockingMode().equals("2");
544     }
545 
546     /**
547      * Check if Graal is used as JIT compiler.
548      *
549      * @return true if Graal is used as JIT compiler.
550      */
551     protected String isGraalEnabled() {
552         return "" + Compiler.isGraalEnabled();
553     }
554 
555     /**
556      * Check if the libgraal shared library file is present.
557      *
558      * @return true if the libgraal shared library file is present.
559      */
560     protected String hasLibgraal() {
561         return "" + WB.hasLibgraal();
562     }
563 
564     /**
565      * Check if libgraal is used as JIT compiler.
566      *
567      * @return true if libgraal is used as JIT compiler.
568      */
569     protected String isLibgraalJIT() {
570         return "" + Compiler.isLibgraalJIT();
571     }
572 
573     /**
574      * Check if Compiler1 is present.
575      *
576      * @return true if Compiler1 is used as JIT compiler, either alone or as part of the tiered system.
577      */
578     protected String isCompiler1Enabled() {
579         return "" + Compiler.isC1Enabled();
580     }
581 
582     /**
583      * Check if Compiler2 is present.
584      *
585      * @return true if Compiler2 is used as JIT compiler, either alone or as part of the tiered system.
586      */
587     protected String isCompiler2Enabled() {
588         return "" + Compiler.isC2Enabled();
589     }
590 
591     protected String isPreviewEnabled() {
592         return "" + PreviewFeatures.isEnabled();
593     }
594     /**
595      * A simple check for container support
596      *
597      * @return true if container is supported in a given environment
598      */
599     protected String containerSupport() {
600         log("Entering containerSupport()");
601 
602         boolean isSupported = false;
603         if (Platform.isLinux()) {
604            // currently container testing is only supported for Linux,
605            // on certain platforms
606 
607            String arch = System.getProperty("os.arch");
608 
609            if (Platform.isX64()) {
610               isSupported = true;
611            } else if (Platform.isAArch64()) {
612               isSupported = true;
613            } else if (Platform.isS390x()) {
614               isSupported = true;
615            } else if (arch.equals("ppc64le")) {
616               isSupported = true;
617            }
618         }
619 
620         log("containerSupport(): platform check: isSupported = " + isSupported);
621 
622         if (isSupported) {
623            try {
624               isSupported = checkProgramSupport("checkContainerSupport()", Container.ENGINE_COMMAND);
625            } catch (Exception e) {
626               isSupported = false;
627            }
628          }
629 
630         log("containerSupport(): returning isSupported = " + isSupported);
631         return "" + isSupported;
632     }
633 
634     /**
635      * A simple check for systemd support
636      *
637      * @return true if systemd is supported in a given environment
638      */
639     protected String systemdSupport() {
640         log("Entering systemdSupport()");
641 
642         boolean isSupported = Platform.isLinux();
643         if (isSupported) {
644            try {
645               isSupported = checkProgramSupport("checkSystemdSupport()", "systemd-run");
646            } catch (Exception e) {
647               isSupported = false;
648            }
649          }
650 
651         log("systemdSupport(): returning isSupported = " + isSupported);
652         return "" + isSupported;
653     }
654 
655     // Configures process builder to redirect process stdout and stderr to a file.
656     // Returns file names for stdout and stderr.
657     private Map<String, String> redirectOutputToLogFile(String msg, ProcessBuilder pb, String fileNameBase) {
658         Map<String, String> result = new HashMap<>();
659         String timeStamp = Instant.now().toString().replace(":", "-").replace(".", "-");
660 
661         String stdoutFileName = String.format("./%s-stdout--%s.log", fileNameBase, timeStamp);
662         pb.redirectOutput(new File(stdoutFileName));
663         log(msg + ": child process stdout redirected to " + stdoutFileName);
664         result.put("stdout", stdoutFileName);
665 
666         String stderrFileName = String.format("./%s-stderr--%s.log", fileNameBase, timeStamp);
667         pb.redirectError(new File(stderrFileName));
668         log(msg + ": child process stderr redirected to " + stderrFileName);
669         result.put("stderr", stderrFileName);
670 
671         return result;
672     }
673 
674     private void printLogfileContent(Map<String, String> logFileNames) {
675         logFileNames.entrySet().stream()
676             .forEach(entry ->
677                 {
678                     log("------------- " + entry.getKey());
679                     try {
680                         Files.lines(Path.of(entry.getValue()))
681                             .forEach(line -> log(line));
682                     } catch (IOException ie) {
683                         log("Exception while reading file: " + ie);
684                     }
685                     log("-------------");
686                 });
687     }
688 
689     private boolean checkProgramSupport(String logString, String cmd) throws IOException, InterruptedException {
690         log(logString + ": entering");
691         ProcessBuilder pb = new ProcessBuilder("which", cmd);
692         Map<String, String> logFileNames =
693             redirectOutputToLogFile(logString + ": which " + cmd,
694                                                       pb, "which-cmd");
695         Process p = pb.start();
696         p.waitFor(10, TimeUnit.SECONDS);
697         int exitValue = p.exitValue();
698 
699         log(String.format("%s: exitValue = %s, pid = %s", logString, exitValue, p.pid()));
700         if (exitValue != 0) {
701             printLogfileContent(logFileNames);
702         }
703 
704         return (exitValue == 0);
705     }
706 
707     /**
708      * Checks musl libc.
709      *
710      * @return true if musl libc is used.
711      */
712     protected String isMusl() {
713         return Boolean.toString(WB.getLibcName().contains("musl"));
714     }
715 
716     private String implementor() {
717         try (InputStream in = new BufferedInputStream(new FileInputStream(
718                 System.getProperty("java.home") + "/release"))) {
719             Properties properties = new Properties();
720             properties.load(in);
721             String implementorProperty = properties.getProperty("IMPLEMENTOR");
722             if (implementorProperty != null) {
723                 return implementorProperty.replace("\"", "");
724             }
725             return errorWithMessage("Can't get 'IMPLEMENTOR' property from 'release' file");
726         } catch (IOException e) {
727             e.printStackTrace();
728             return errorWithMessage("Failed to read 'release' file " + e);
729         }
730     }
731 
732     private String jdkContainerized() {
733         String isEnabled = System.getenv("TEST_JDK_CONTAINERIZED");
734         return "" + "true".equalsIgnoreCase(isEnabled);
735     }
736 
737     private String packagedModules() {
738         // Some jlink tests require packaged modules being present (jmods).
739         // For a runtime linkable image build packaged modules aren't present
740         try {
741             Path jmodsDir = Path.of(System.getProperty("java.home"), "jmods");
742             if (jmodsDir.toFile().exists()) {
743                 return Boolean.TRUE.toString();
744             } else {
745                 return Boolean.FALSE.toString();
746             }
747         } catch (Throwable t) {
748             return Boolean.FALSE.toString();
749         }
750     }
751 
752     /**
753      * Checks if we are in <i>almost</i> out-of-box configuration, i.e. the flags
754      * which JVM is started with don't affect its behavior "significantly".
755      * {@code TEST_VM_FLAGLESS} enviroment variable can be used to force this
756      * method to return true or false and allow or reject any flags.
757      *
758      * @return true if there are no JVM flags
759      */
760     private String isFlagless() {
761         boolean result = true;
762         String flagless = System.getenv("TEST_VM_FLAGLESS");
763         if (flagless != null) {
764             return "" + "true".equalsIgnoreCase(flagless);
765         }
766 
767         List<String> allFlags = allFlags().toList();
768 
769         // check -XX flags
770         var ignoredXXFlags = Set.of(
771                 // added by run-test framework
772                 "MaxRAMPercentage",
773                 // added by test environment
774                 "CreateCoredumpOnCrash"
775         );
776         result &= allFlags.stream()
777                           .filter(s -> s.startsWith("-XX:"))
778                           // map to names:
779                               // remove -XX:
780                               .map(s -> s.substring(4))
781                               // remove +/- from bool flags
782                               .map(s -> s.charAt(0) == '+' || s.charAt(0) == '-' ? s.substring(1) : s)
783                               // remove =.* from others
784                               .map(s -> s.contains("=") ? s.substring(0, s.indexOf('=')) : s)
785                           // skip known-to-be-there flags
786                           .filter(s -> !ignoredXXFlags.contains(s))
787                           .findAny()
788                           .isEmpty();
789 
790         // check -X flags
791         var ignoredXFlags = Set.of(
792                 // default, yet still seen to be explicitly set
793                 "mixed",
794                 // -XmxmNNNm added by run-test framework for non-hotspot tests
795                 "mx"
796         );
797         result &= allFlags.stream()
798                           .filter(s -> s.startsWith("-X") && !s.startsWith("-XX:"))
799                           // map to names:
800                           // remove -X
801                           .map(s -> s.substring(2))
802                           // remove :.* from flags with values
803                           .map(s -> s.contains(":") ? s.substring(0, s.indexOf(':')) : s)
804                           // remove size like 4G, 768m which might be set for non-hotspot tests
805                           .map(s -> s.replaceAll("(\\d+)[mMgGkK]", ""))
806                           // skip known-to-be-there flags
807                           .filter(s -> !ignoredXFlags.contains(s))
808                           .findAny()
809                           .isEmpty();
810 
811         return "" + result;
812     }
813 
814     private Stream<String> allFlags() {
815         return Stream.of((System.getProperty("test.vm.opts", "") + " " + System.getProperty("test.java.opts", "")).trim().split("\\s+"));
816     }
817 
818     /*
819      * A string indicating the foreign linker that is currently being used. See jdk.internal.foreign.CABI
820      * for valid values.
821      *
822      * "FALLBACK" and "UNSUPPORTED" are special values. The former indicates the fallback linker is
823      * being used. The latter indicates an unsupported platform.
824      */
825     private String jdkForeignLinker() {
826         return String.valueOf(CABI.current());
827     }
828 
829     private String isStatic() {
830         return Boolean.toString(WB.isStatic());
831     }
832 
833     /**
834      * Dumps the map to the file if the file name is given as the property.
835      * This functionality could be helpful to know context in the real
836      * execution.
837      *
838      * @param map
839      */
840     protected static void dump(Map<String, String> map) {
841         String dumpFileName = System.getProperty("vmprops.dump");
842         if (dumpFileName == null) {
843             return;
844         }
845         List<String> lines = new ArrayList<>();
846         map.forEach((k, v) -> lines.add(k + ":" + v));
847         Collections.sort(lines);
848         try {
849             Files.write(Paths.get(dumpFileName), lines,
850                     StandardOpenOption.APPEND, StandardOpenOption.CREATE);
851         } catch (IOException e) {
852             throw new RuntimeException("Failed to dump properties into '"
853                     + dumpFileName + "'", e);
854         }
855     }
856 
857     /**
858      * Log diagnostic message.
859      *
860      * @param msg
861      */
862     protected static void log(String msg) {
863         // Always log to a file.
864         logToFile(msg);
865 
866         // Also log to stderr; guarded by property to avoid excessive verbosity.
867         // By jtreg design stderr produced here will be visible
868         // in the output of a parent process. Note: stdout should not be used
869         // for logging as jtreg parses that output directly and only echoes it
870         // in the event of a failure.
871         if (Boolean.getBoolean("jtreg.log.vmprops")) {
872             System.err.println("VMProps: " + msg);
873         }
874     }
875 
876     /**
877      * Log diagnostic message to a file.
878      *
879      * @param msg
880      */
881     protected static void logToFile(String msg) {
882         String fileName = "./vmprops.log";
883         try {
884             Files.writeString(Paths.get(fileName), msg + "\n", Charset.forName("ISO-8859-1"),
885                     StandardOpenOption.APPEND, StandardOpenOption.CREATE);
886         } catch (IOException e) {
887             throw new RuntimeException("Failed to log into '" + fileName + "'", e);
888         }
889     }
890 
891     /**
892      * This method is for the testing purpose only.
893      *
894      * @param args
895      */
896     public static void main(String args[]) {
897         Map<String, String> map = new VMProps().call();
898         map.forEach((k, v) -> System.out.println(k + ": '" + v + "'"));
899     }
900 }