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