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