1 /*
  2  * Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 package requires;
 25 
 26 import java.io.BufferedInputStream;
 27 import java.io.FileInputStream;
 28 import java.io.IOException;
 29 import java.io.InputStream;
 30 import java.io.File;
 31 import java.nio.charset.Charset;
 32 import java.nio.file.Files;
 33 import java.nio.file.Path;
 34 import java.nio.file.Paths;
 35 import java.nio.file.StandardOpenOption;
 36 import java.time.Instant;
 37 import java.util.ArrayList;
 38 import java.util.Collections;
 39 import java.util.HashMap;
 40 import java.util.List;
 41 import java.util.Map;
 42 import java.util.Properties;
 43 import java.util.Set;
 44 import java.util.concurrent.Callable;
 45 import java.util.concurrent.TimeUnit;
 46 import java.util.function.Predicate;
 47 import java.util.function.Supplier;
 48 import java.util.regex.Matcher;
 49 import java.util.regex.Pattern;
 50 import java.util.stream.Stream;
 51 
 52 import jdk.internal.foreign.CABI;
 53 import jdk.internal.misc.PreviewFeatures;
 54 import jdk.test.whitebox.code.Compiler;
 55 import jdk.test.whitebox.cpuinfo.CPUInfo;
 56 import jdk.test.whitebox.gc.GC;
 57 import jdk.test.whitebox.WhiteBox;
 58 import jdk.test.lib.Platform;
 59 import jdk.test.lib.Container;
 60 
 61 /**
 62  * The Class to be invoked by jtreg prior Test Suite execution to
 63  * collect information about VM.
 64  * Do not use any APIs that may not be available in all target VMs.
 65  * Properties set by this Class will be available in the @requires expressions.
 66  */
 67 public class VMProps implements Callable<Map<String, String>> {
 68     // value known to jtreg as an indicator of error state
 69     private static final String ERROR_STATE = "__ERROR__";
 70 
 71     private static final String GC_PREFIX = "-XX:+Use";
 72     private static final String GC_SUFFIX = "GC";
 73 
 74     private static final WhiteBox WB = WhiteBox.getWhiteBox();
 75 
 76     private static class SafeMap {
 77         private final Map<String, String> map = new HashMap<>();
 78 
 79         public void put(String key, Supplier<String> s) {
 80             String value;
 81             try {
 82                 value = s.get();
 83             } catch (Throwable t) {
 84                 System.err.println("failed to get value for " + key);
 85                 t.printStackTrace(System.err);
 86                 value = ERROR_STATE + t;
 87             }
 88             map.put(key, value);
 89         }
 90     }
 91 
 92     /**
 93      * Collects information about VM properties.
 94      * This method will be invoked by jtreg.
 95      *
 96      * @return Map of property-value pairs.
 97      */
 98     @Override
 99     public Map<String, String> call() {
100         log("Entering call()");
101         SafeMap map = new SafeMap();
102         map.put("vm.flavor", this::vmFlavor);
103         map.put("vm.compMode", this::vmCompMode);
104         map.put("vm.bits", this::vmBits);
105         map.put("vm.flightRecorder", this::vmFlightRecorder);
106         map.put("vm.simpleArch", this::vmArch);
107         map.put("vm.debug", this::vmDebug);
108         // vm.hasSA is "true" if the VM contains the serviceability agent
109         // and jhsdb.
110         map.put("vm.hasSA", this::vmHasSA);
111         // vm.hasJFR is "true" if JFR is included in the build of the VM and
112         // so tests can be executed.
113         map.put("vm.hasJFR", this::vmHasJFR);
114         map.put("vm.hasDTrace", this::vmHasDTrace);
115         map.put("vm.jvmti", this::vmHasJVMTI);
116         map.put("vm.cpu.features", this::cpuFeatures);
117         map.put("vm.pageSize", this::vmPageSize);
118         // vm.cds is true if the VM is compiled with cds support.
119         map.put("vm.cds", this::vmCDS);
120         map.put("vm.cds.default.archive.available", this::vmCDSDefaultArchiveAvailable);
121         map.put("vm.cds.nocoops.archive.available", this::vmCDSNocoopsArchiveAvailable);
122         map.put("vm.cds.nocoh.archive.available", this::vmCDSNocohArchiveAvailable);
123         map.put("vm.cds.custom.loaders", this::vmCDSForCustomLoaders);
124         map.put("vm.cds.supports.aot.class.linking", this::vmCDSSupportsAOTClassLinking);
125         map.put("vm.cds.supports.aot.code.caching", this::vmCDSSupportsAOTCodeCaching);
126         map.put("vm.cds.write.archived.java.heap", this::vmCDSCanWriteArchivedJavaHeap);
127         map.put("vm.cds.write.mapped.java.heap", this::vmCDSCanWriteMappedArchivedJavaHeap);
128         map.put("vm.cds.write.streamed.java.heap", this::vmCDSCanWriteStreamedArchivedJavaHeap);
129         map.put("vm.continuations", this::vmContinuations);
130         map.put("java.enablePreview", this::isPreviewEnabled);
131         map.put("vm.compiler1.enabled", this::isCompiler1Enabled);
132         map.put("vm.compiler2.enabled", this::isCompiler2Enabled);
133         map.put("container.support", this::containerSupport);
134         map.put("systemd.support", this::systemdSupport);
135         map.put("vm.musl", this::isMusl);
136         map.put("vm.asan", this::isAsanEnabled);
137         map.put("vm.ubsan", this::isUbsanEnabled);
138         map.put("release.implementor", this::implementor);
139         map.put("jdk.containerized", this::jdkContainerized);
140         map.put("vm.flagless", this::isFlagless);
141         map.put("jdk.foreign.linker", this::jdkForeignLinker);
142         map.put("jdk.explodedImage", this::explodedImage);
143         map.put("jlink.packagedModules", this::packagedModules);
144         map.put("jdk.static", this::isStatic);
145         vmGC(map); // vm.gc.X = true/false
146         vmGCforCDS(map); // may set vm.gc
147         vmOptFinalFlags(map);
148         vmOptFinalIntxFlags(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 supported CPU features
262      */
263     protected String cpuFeatures() {
264         return CPUInfo.getFeatures().toString();
265     }
266 
267     /**
268      * For all existing GC sets vm.gc.X property.
269      * Example vm.gc.G1=true means:
270      *    VM supports G1
271      *    User either set G1 explicitely (-XX:+UseG1GC) or did not set any GC
272      *    G1 can be selected, i.e. it doesn't conflict with other VM flags
273      *
274      * @param map - property-value pairs
275      */
276     protected void vmGC(SafeMap map) {
277         Predicate<GC> vmGCProperty = (GC gc) -> (gc.isSupported()
278                                         && (gc.isSelected() || GC.isSelectedErgonomically()));
279         for (GC gc: GC.values()) {
280             map.put("vm.gc." + gc.name(), () -> "" + vmGCProperty.test(gc));
281         }
282     }
283 
284     /**
285      * "jtreg -vmoptions:-Dtest.cds.runtime.options=..." can be used to specify
286      * the GC type to be used when running with a CDS archive. Set "vm.gc" accordingly,
287      * so that tests that need to explicitly choose the GC type can be excluded
288      * with "@requires vm.gc == null".
289      *
290      * @param map - property-value pairs
291      */
292     protected void vmGCforCDS(SafeMap map) {
293         if (!GC.isSelectedErgonomically()) {
294             // The GC has been explicitly specified on the command line, so
295             // jtreg will set the "vm.gc" property. Let's not interfere with it.
296             return;
297         }
298 
299         String jtropts = System.getProperty("test.cds.runtime.options");
300         if (jtropts != null) {
301             for (String opt : jtropts.split(",")) {
302                 if (opt.startsWith(GC_PREFIX) && opt.endsWith(GC_SUFFIX)) {
303                     String gc = opt.substring(GC_PREFIX.length(), opt.length() - GC_SUFFIX.length());
304                     map.put("vm.gc", () -> gc);
305                 }
306             }
307         }
308     }
309 
310     /**
311      * Selected final flag.
312      *
313      * @param map - property-value pairs
314      * @param flagName - flag name
315      */
316     private void vmOptFinalFlag(SafeMap map, String flagName) {
317         map.put("vm.opt.final." + flagName,
318                 () -> String.valueOf(WB.getBooleanVMFlag(flagName)));
319     }
320 
321     /**
322      * Selected sets of final flags.
323      *
324      * @param map - property-value pairs
325      */
326     protected void vmOptFinalFlags(SafeMap map) {
327         vmOptFinalFlag(map, "ClassUnloading");
328         vmOptFinalFlag(map, "ClassUnloadingWithConcurrentMark");
329         vmOptFinalFlag(map, "CriticalJNINatives");
330         vmOptFinalFlag(map, "EliminateAllocations");
331         vmOptFinalFlag(map, "TieredCompilation");
332         vmOptFinalFlag(map, "UnlockExperimentalVMOptions");
333         vmOptFinalFlag(map, "UseAdaptiveSizePolicy");
334         vmOptFinalFlag(map, "UseCompressedOops");
335         vmOptFinalFlag(map, "UseLargePages");
336         vmOptFinalFlag(map, "UseTransparentHugePages");
337         vmOptFinalFlag(map, "UseVectorizedMismatchIntrinsic");
338     }
339 
340     /**
341      * Selected final flag of type intx.
342      *
343      * @param map - property-value pairs
344      * @param flagName - flag name
345      */
346     private void vmOptFinalIntxFlag(SafeMap map, String flagName) {
347         map.put("vm.opt.final." + flagName,
348                 () -> String.valueOf(WB.getIntxVMFlag(flagName)));
349     }
350 
351     /**
352      * Selected sets of final flags of type intx.
353      *
354      * @param map - property-value pairs
355      */
356     protected void vmOptFinalIntxFlags(SafeMap map) {
357         vmOptFinalIntxFlag(map, "MaxVectorSize");
358     }
359 
360     /**
361      * @return "true" if VM has a serviceability agent.
362      */
363     protected String vmHasSA() {
364         return "" + Platform.hasSA();
365     }
366 
367     /**
368      * @return "true" if the VM is compiled with Java Flight Recorder (JFR)
369      * support.
370      */
371     protected String vmHasJFR() {
372         return "" + WB.isJFRIncluded();
373     }
374 
375     /**
376      * @return "true" if the VM is compiled with JVMTI
377      */
378     protected String vmHasJVMTI() {
379         return "" + WB.isJVMTIIncluded();
380     }
381 
382     /**
383      * @return "true" if the VM is compiled with DTrace
384      */
385     protected String vmHasDTrace() {
386         return "" + WB.isDTraceIncluded();
387     }
388 
389     /**
390      * Check for CDS support.
391      *
392      * @return true if CDS is supported by the VM to be tested.
393      */
394     protected String vmCDS() {
395         boolean noJvmtiAdded = allFlags()
396                 .filter(s -> s.startsWith("-agentpath"))
397                 .findAny()
398                 .isEmpty();
399 
400         return "" + (noJvmtiAdded && WB.isCDSIncluded());
401     }
402 
403     /**
404      * Check for CDS default archive existence.
405      *
406      * @return true if CDS default archive classes.jsa exists in the JDK to be tested.
407      */
408     protected String vmCDSDefaultArchiveAvailable() {
409         Path archive = Paths.get(System.getProperty("java.home"), "lib", "server", "classes.jsa");
410         return "" + ("true".equals(vmCDS()) && Files.exists(archive));
411     }
412 
413     /**
414      * Check for CDS no compressed oops archive existence.
415      *
416      * @return true if CDS archive classes_nocoops.jsa exists in the JDK to be tested.
417      */
418     protected String vmCDSNocoopsArchiveAvailable() {
419         Path archive = Paths.get(System.getProperty("java.home"), "lib", "server", "classes_nocoops.jsa");
420         return "" + ("true".equals(vmCDS()) && Files.exists(archive));
421     }
422 
423     /**
424      * Check for CDS no compact object headers archive existence.
425      *
426      * @return true if CDS archive classes_nocoh.jsa exists in the JDK to be tested.
427      */
428     protected String vmCDSNocohArchiveAvailable() {
429         Path archive = Paths.get(System.getProperty("java.home"), "lib", "server", "classes_nocoh.jsa");
430         return "" + ("true".equals(vmCDS()) && Files.exists(archive));
431     }
432 
433     /**
434      * Check for CDS support for custom loaders.
435      *
436      * @return true if CDS provides support for customer loader in the VM to be tested.
437      */
438     protected String vmCDSForCustomLoaders() {
439         return "" + ("true".equals(vmCDS()) && Platform.areCustomLoadersSupportedForCDS());
440     }
441 
442     /**
443      * @return true if it's possible for "java -Xshare:dump" to write Java heap objects
444      *         with the current set of jtreg VM options.
445      */
446     protected String vmCDSCanWriteArchivedJavaHeap() {
447         return "" + ("true".equals(vmCDS()) && WB.canWriteJavaHeapArchive());
448     }
449 
450     /**
451      * @return true if it's possible for "java -Xshare:dump" to write Java heap objects
452      *         with the current set of jtreg VM options.
453      */
454     protected String vmCDSCanWriteMappedArchivedJavaHeap() {
455         return "" + ("true".equals(vmCDS()) && WB.canWriteMappedJavaHeapArchive());
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.
461      */
462     protected String vmCDSCanWriteStreamedArchivedJavaHeap() {
463         return "" + ("true".equals(vmCDS()) && WB.canWriteStreamedJavaHeapArchive());
464     }
465 
466     /**
467      * @return true if this VM can support the -XX:AOTClassLinking option
468      */
469     protected String vmCDSSupportsAOTClassLinking() {
470       // Currently, the VM supports AOTClassLinking as long as it's able to write archived java heap.
471       return vmCDSCanWriteArchivedJavaHeap();
472     }
473 
474     /**
475      * @return true if this VM can support the AOT Code Caching
476      */
477     protected String vmCDSSupportsAOTCodeCaching() {
478       if ("true".equals(vmCDSSupportsAOTClassLinking()) &&
479           !"zero".equals(vmFlavor()) &&
480           (Platform.isX64() || Platform.isAArch64())) {
481         return "true";
482       } else {
483         return "false";
484       }
485     }
486 
487     /**
488      * @return "true" if this VM supports continuations.
489      */
490     protected String vmContinuations() {
491         if (WB.getBooleanVMFlag("VMContinuations")) {
492             return "true";
493         } else {
494             return "false";
495         }
496     }
497 
498     /**
499      * @return System page size in bytes.
500      */
501     protected String vmPageSize() {
502         return "" + WB.getVMPageSize();
503     }
504 
505     /**
506      * Check if Compiler1 is present.
507      *
508      * @return true if Compiler1 is used as JIT compiler, either alone or as part of the tiered system.
509      */
510     protected String isCompiler1Enabled() {
511         return "" + Compiler.isC1Enabled();
512     }
513 
514     /**
515      * Check if Compiler2 is present.
516      *
517      * @return true if Compiler2 is used as JIT compiler, either alone or as part of the tiered system.
518      */
519     protected String isCompiler2Enabled() {
520         return "" + Compiler.isC2Enabled();
521     }
522 
523     protected String isPreviewEnabled() {
524         return "" + PreviewFeatures.isEnabled();
525     }
526     /**
527      * A simple check for container support
528      *
529      * @return true if container is supported in a given environment
530      */
531     protected String containerSupport() {
532         log("Entering containerSupport()");
533 
534         boolean isSupported = false;
535         if (Platform.isLinux()) {
536            // currently container testing is only supported for Linux,
537            // on certain platforms
538 
539            String arch = System.getProperty("os.arch");
540 
541            if (Platform.isX64()) {
542               isSupported = true;
543            } else if (Platform.isAArch64()) {
544               isSupported = true;
545            } else if (Platform.isS390x()) {
546               isSupported = true;
547            } else if (arch.equals("ppc64le")) {
548               isSupported = true;
549            }
550         }
551 
552         log("containerSupport(): platform check: isSupported = " + isSupported);
553 
554         if (isSupported) {
555            try {
556               isSupported = checkProgramSupport("checkContainerSupport()", Container.ENGINE_COMMAND);
557            } catch (Exception e) {
558               isSupported = false;
559            }
560          }
561 
562         log("containerSupport(): returning isSupported = " + isSupported);
563         return "" + isSupported;
564     }
565 
566     /**
567      * A simple check for systemd support
568      *
569      * @return true if systemd is supported in a given environment
570      */
571     protected String systemdSupport() {
572         log("Entering systemdSupport()");
573 
574         boolean isSupported = Platform.isLinux();
575         if (isSupported) {
576            try {
577               isSupported = checkProgramSupport("checkSystemdSupport()", "systemd-run");
578            } catch (Exception e) {
579               isSupported = false;
580            }
581          }
582 
583         log("systemdSupport(): returning isSupported = " + isSupported);
584         return "" + isSupported;
585     }
586 
587     // Configures process builder to redirect process stdout and stderr to a file.
588     // Returns file names for stdout and stderr.
589     private Map<String, String> redirectOutputToLogFile(String msg, ProcessBuilder pb, String fileNameBase) {
590         Map<String, String> result = new HashMap<>();
591         String timeStamp = Instant.now().toString().replace(":", "-").replace(".", "-");
592 
593         String stdoutFileName = String.format("./%s-stdout--%s.log", fileNameBase, timeStamp);
594         pb.redirectOutput(new File(stdoutFileName));
595         log(msg + ": child process stdout redirected to " + stdoutFileName);
596         result.put("stdout", stdoutFileName);
597 
598         String stderrFileName = String.format("./%s-stderr--%s.log", fileNameBase, timeStamp);
599         pb.redirectError(new File(stderrFileName));
600         log(msg + ": child process stderr redirected to " + stderrFileName);
601         result.put("stderr", stderrFileName);
602 
603         return result;
604     }
605 
606     private void printLogfileContent(Map<String, String> logFileNames) {
607         logFileNames.entrySet().stream()
608             .forEach(entry ->
609                 {
610                     log("------------- " + entry.getKey());
611                     try {
612                         Files.lines(Path.of(entry.getValue()))
613                             .forEach(line -> log(line));
614                     } catch (IOException ie) {
615                         log("Exception while reading file: " + ie);
616                     }
617                     log("-------------");
618                 });
619     }
620 
621     private boolean checkProgramSupport(String logString, String cmd) throws IOException, InterruptedException {
622         log(logString + ": entering");
623         ProcessBuilder pb = new ProcessBuilder("which", cmd);
624         Map<String, String> logFileNames =
625             redirectOutputToLogFile(logString + ": which " + cmd,
626                                                       pb, "which-cmd");
627         Process p = pb.start();
628         p.waitFor(10, TimeUnit.SECONDS);
629         int exitValue = p.exitValue();
630 
631         log(String.format("%s: exitValue = %s, pid = %s", logString, exitValue, p.pid()));
632         if (exitValue != 0) {
633             printLogfileContent(logFileNames);
634         }
635 
636         return (exitValue == 0);
637     }
638 
639     /**
640      * Checks musl libc.
641      *
642      * @return true if musl libc is used.
643      */
644     protected String isMusl() {
645         return Boolean.toString(WB.getLibcName().contains("musl"));
646     }
647 
648     // Sanitizer support
649     protected String isAsanEnabled() {
650         return "" + WB.isAsanEnabled();
651     }
652 
653     protected String isUbsanEnabled() {
654         return "" + WB.isUbsanEnabled();
655     }
656 
657     private String implementor() {
658         try (InputStream in = new BufferedInputStream(new FileInputStream(
659                 System.getProperty("java.home") + "/release"))) {
660             Properties properties = new Properties();
661             properties.load(in);
662             String implementorProperty = properties.getProperty("IMPLEMENTOR");
663             if (implementorProperty != null) {
664                 return implementorProperty.replace("\"", "");
665             }
666             return errorWithMessage("Can't get 'IMPLEMENTOR' property from 'release' file");
667         } catch (IOException e) {
668             e.printStackTrace();
669             return errorWithMessage("Failed to read 'release' file " + e);
670         }
671     }
672 
673     private String jdkContainerized() {
674         String isEnabled = System.getenv("TEST_JDK_CONTAINERIZED");
675         return "" + "true".equalsIgnoreCase(isEnabled);
676     }
677 
678     private String explodedImage() {
679         try {
680             Path jmodFile = Path.of(System.getProperty("java.home"), "jmods", "java.base.jmod");
681             if (Files.exists(jmodFile)) {
682                 return Boolean.FALSE.toString();
683             } else {
684                 return Boolean.TRUE.toString();
685             }
686         } catch (Throwable t) {
687             t.printStackTrace();
688             return errorWithMessage("Error in explodedImage " + t);
689         }
690     }
691 
692     private String packagedModules() {
693         // Some jlink tests require packaged modules being present (jmods).
694         // For a runtime linkable image build packaged modules aren't present
695         try {
696             Path jmodsDir = Path.of(System.getProperty("java.home"), "jmods");
697             if (jmodsDir.toFile().exists()) {
698                 return Boolean.TRUE.toString();
699             } else {
700                 return Boolean.FALSE.toString();
701             }
702         } catch (Throwable t) {
703             return Boolean.FALSE.toString();
704         }
705     }
706 
707     /**
708      * Checks if we are in <i>almost</i> out-of-box configuration, i.e. the flags
709      * which JVM is started with don't affect its behavior "significantly".
710      * {@code TEST_VM_FLAGLESS} enviroment variable can be used to force this
711      * method to return true or false and allow or reject any flags.
712      *
713      * @return true if there are no JVM flags
714      */
715     private String isFlagless() {
716         boolean result = true;
717         String flagless = System.getenv("TEST_VM_FLAGLESS");
718         if (flagless != null) {
719             return "" + "true".equalsIgnoreCase(flagless);
720         }
721 
722         List<String> allFlags = allFlags().toList();
723 
724         // check -XX flags
725         var ignoredXXFlags = Set.of(
726                 // added by run-test framework
727                 "MaxRAMPercentage",
728                 // added by test environment
729                 "CreateCoredumpOnCrash"
730         );
731         result &= allFlags.stream()
732                           .filter(s -> s.startsWith("-XX:"))
733                           // map to names:
734                               // remove -XX:
735                               .map(s -> s.substring(4))
736                               // remove +/- from bool flags
737                               .map(s -> s.charAt(0) == '+' || s.charAt(0) == '-' ? s.substring(1) : s)
738                               // remove =.* from others
739                               .map(s -> s.contains("=") ? s.substring(0, s.indexOf('=')) : s)
740                           // skip known-to-be-there flags
741                           .filter(s -> !ignoredXXFlags.contains(s))
742                           .findAny()
743                           .isEmpty();
744 
745         // check -X flags
746         var ignoredXFlags = Set.of(
747                 // default, yet still seen to be explicitly set
748                 "mixed",
749                 // -XmxmNNNm added by run-test framework for non-hotspot tests
750                 "mx"
751         );
752         result &= allFlags.stream()
753                           .filter(s -> s.startsWith("-X") && !s.startsWith("-XX:"))
754                           // map to names:
755                           // remove -X
756                           .map(s -> s.substring(2))
757                           // remove :.* from flags with values
758                           .map(s -> s.contains(":") ? s.substring(0, s.indexOf(':')) : s)
759                           // remove size like 4G, 768m which might be set for non-hotspot tests
760                           .map(s -> s.replaceAll("(\\d+)[mMgGkK]", ""))
761                           // skip known-to-be-there flags
762                           .filter(s -> !ignoredXFlags.contains(s))
763                           .findAny()
764                           .isEmpty();
765 
766         return "" + result;
767     }
768 
769     private Stream<String> allFlags() {
770         return Stream.of((System.getProperty("test.vm.opts", "") + " " + System.getProperty("test.java.opts", "")).trim().split("\\s+"));
771     }
772 
773     /*
774      * A string indicating the foreign linker that is currently being used. See jdk.internal.foreign.CABI
775      * for valid values.
776      *
777      * "FALLBACK" and "UNSUPPORTED" are special values. The former indicates the fallback linker is
778      * being used. The latter indicates an unsupported platform.
779      */
780     private String jdkForeignLinker() {
781         return String.valueOf(CABI.current());
782     }
783 
784     private String isStatic() {
785         return Boolean.toString(WB.isStatic());
786     }
787 
788     /**
789      * Dumps the map to the file if the file name is given as the property.
790      * This functionality could be helpful to know context in the real
791      * execution.
792      *
793      * @param map
794      */
795     protected static void dump(Map<String, String> map) {
796         String dumpFileName = System.getProperty("vmprops.dump");
797         if (dumpFileName == null) {
798             return;
799         }
800         List<String> lines = new ArrayList<>();
801         map.forEach((k, v) -> lines.add(k + ":" + v));
802         Collections.sort(lines);
803         try {
804             Files.write(Paths.get(dumpFileName), lines,
805                     StandardOpenOption.APPEND, StandardOpenOption.CREATE);
806         } catch (IOException e) {
807             throw new RuntimeException("Failed to dump properties into '"
808                     + dumpFileName + "'", e);
809         }
810     }
811 
812     /**
813      * Log diagnostic message.
814      *
815      * @param msg
816      */
817     protected static void log(String msg) {
818         // Always log to a file.
819         logToFile(msg);
820 
821         // Also log to stderr; guarded by property to avoid excessive verbosity.
822         // By jtreg design stderr produced here will be visible
823         // in the output of a parent process. Note: stdout should not be used
824         // for logging as jtreg parses that output directly and only echoes it
825         // in the event of a failure.
826         if (Boolean.getBoolean("jtreg.log.vmprops")) {
827             System.err.println("VMProps: " + msg);
828         }
829     }
830 
831     /**
832      * Log diagnostic message to a file.
833      *
834      * @param msg
835      */
836     protected static void logToFile(String msg) {
837         String fileName = "./vmprops.log";
838         try {
839             Files.writeString(Paths.get(fileName), msg + "\n", Charset.forName("ISO-8859-1"),
840                     StandardOpenOption.APPEND, StandardOpenOption.CREATE);
841         } catch (IOException e) {
842             throw new RuntimeException("Failed to log into '" + fileName + "'", e);
843         }
844     }
845 
846     /**
847      * This method is for the testing purpose only.
848      *
849      * @param args
850      */
851     public static void main(String args[]) {
852         Map<String, String> map = new VMProps().call();
853         map.forEach((k, v) -> System.out.println(k + ": '" + v + "'"));
854     }
855 }