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