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