1 /*
   2 * Copyright (c) 2013, 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 import java.util.regex.Matcher;
  25 import java.util.regex.Pattern;
  26 import java.util.ArrayList;
  27 import java.util.Arrays;
  28 
  29 import com.oracle.java.testlibrary.*;
  30 import sun.hotspot.WhiteBox;
  31 
  32 class ErgoArgsPrinter {
  33   public static void main(String[] args) throws Exception {
  34     WhiteBox wb = WhiteBox.getWhiteBox();
  35     wb.printHeapSizes();
  36   }
  37 }
  38 
  39 final class MinInitialMaxValues {
  40   public long minHeapSize;
  41   public long initialHeapSize;
  42   public long maxHeapSize;
  43 
  44   public long minAlignment;
  45   public long maxAlignment;
  46 }
  47 
  48 class TestMaxHeapSizeTools {
  49 
  50   public static void checkMinInitialMaxHeapFlags(String gcflag) throws Exception {
  51     checkInvalidMinInitialHeapCombinations(gcflag);
  52     checkValidMinInitialHeapCombinations(gcflag);
  53     checkInvalidInitialMaxHeapCombinations(gcflag);
  54     checkValidInitialMaxHeapCombinations(gcflag);
  55   }
  56 
  57   public static void checkMinInitialErgonomics(String gcflag) throws Exception {
  58     // heap sizing ergonomics use the value NewSize + OldSize as default values
  59     // for ergonomics calculation. Retrieve these values.
  60     long[] values = new long[2];
  61     getNewOldSize(gcflag, values);
  62 
  63     // we check cases with values smaller and larger than this default value.
  64     long newPlusOldSize = values[0] + values[1];
  65     long smallValue = newPlusOldSize / 2;
  66     long largeValue = newPlusOldSize * 2;
  67 
  68     // -Xms is not set
  69     checkErgonomics(new String[] { gcflag, "-Xmx16M" }, values, -1, -1);
  70     checkErgonomics(new String[] { gcflag, "-Xmx16M", "-XX:InitialHeapSize=" + smallValue }, values, smallValue, smallValue);
  71     checkErgonomics(new String[] { gcflag, "-Xmx16M", "-XX:InitialHeapSize=" + largeValue }, values, -1, largeValue);
  72     checkErgonomics(new String[] { gcflag, "-Xmx16M", "-XX:InitialHeapSize=0" }, values, -1, -1);
  73 
  74     // -Xms is set to zero
  75     checkErgonomics(new String[] { gcflag, "-Xmx16M", "-Xms0" }, values, -1, -1);
  76     checkErgonomics(new String[] { gcflag, "-Xmx16M", "-Xms0", "-XX:InitialHeapSize=" + smallValue }, values, smallValue, smallValue);
  77     checkErgonomics(new String[] { gcflag, "-Xmx16M", "-Xms0", "-XX:InitialHeapSize=" + largeValue }, values, -1, largeValue);
  78     checkErgonomics(new String[] { gcflag, "-Xmx16M", "-Xms0", "-XX:InitialHeapSize=0" }, values, -1, -1);
  79 
  80     // -Xms is set to small value
  81     checkErgonomics(new String[] { gcflag, "-Xmx16M", "-Xms" + smallValue }, values, -1, -1);
  82     checkErgonomics(new String[] { gcflag, "-Xmx16M", "-Xms" + smallValue, "-XX:InitialHeapSize=" + smallValue }, values, smallValue, smallValue);
  83     checkErgonomics(new String[] { gcflag, "-Xmx16M", "-Xms" + smallValue, "-XX:InitialHeapSize=" + largeValue }, values, smallValue, largeValue);
  84     checkErgonomics(new String[] { gcflag, "-Xmx16M", "-Xms" + smallValue, "-XX:InitialHeapSize=0" }, values, smallValue, -1);
  85 
  86     // -Xms is set to large value
  87     checkErgonomics(new String[] { gcflag, "-Xmx16M", "-Xms" + largeValue }, values, largeValue, largeValue);
  88     // the next case has already been checked elsewhere and gives an error
  89     // checkErgonomics(new String[] { gcflag, "-Xmx16M", "-Xms" + largeValue, "-XX:InitialHeapSize=" + smallValue }, values, smallValue, smallValue);
  90     // the next case has already been checked elsewhere too
  91     // checkErgonomics(new String[] { gcflag, "-Xmx16M", "-Xms" + largeValue, "-XX:InitialHeapSize=" + largeValue }, values, values[0], largeValue);
  92     checkErgonomics(new String[] { gcflag, "-Xmx16M", "-Xms" + largeValue, "-XX:InitialHeapSize=0" }, values, largeValue, -1);
  93   }
  94 
  95   private static long align_up(long value, long alignment) {
  96     long alignmentMinusOne = alignment - 1;
  97     return (value + alignmentMinusOne) & ~alignmentMinusOne;
  98   }
  99 
 100   private static void getNewOldSize(String gcflag, long[] values) throws Exception {
 101     ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(gcflag,
 102       "-XX:+PrintFlagsFinal", "-version");
 103     OutputAnalyzer output = new OutputAnalyzer(pb.start());
 104     output.shouldHaveExitValue(0);
 105 
 106     String stdout = output.getStdout();
 107     values[0] = getFlagValue(" NewSize", stdout);
 108     values[1] = getFlagValue(" OldSize", stdout);
 109   }
 110 
 111   public static void checkGenMaxHeapErgo(String gcflag) throws Exception {
 112     TestMaxHeapSizeTools.checkGenMaxHeapSize(gcflag, 3);
 113     TestMaxHeapSizeTools.checkGenMaxHeapSize(gcflag, 4);
 114     TestMaxHeapSizeTools.checkGenMaxHeapSize(gcflag, 5);
 115   }
 116 
 117   private static void checkInvalidMinInitialHeapCombinations(String gcflag) throws Exception {
 118     expectError(new String[] { gcflag, "-Xms8M", "-XX:InitialHeapSize=4M", "-version" });
 119   }
 120 
 121   private static void checkValidMinInitialHeapCombinations(String gcflag) throws Exception {
 122     expectValid(new String[] { gcflag, "-XX:InitialHeapSize=8M", "-Xms4M", "-version" });
 123     expectValid(new String[] { gcflag, "-Xms4M", "-XX:InitialHeapSize=8M", "-version" });
 124     expectValid(new String[] { gcflag, "-XX:InitialHeapSize=8M", "-Xms8M", "-version" });
 125     // the following is not an error as -Xms sets both minimal and initial heap size
 126     expectValid(new String[] { gcflag, "-XX:InitialHeapSize=4M", "-Xms8M", "-version" });
 127   }
 128 
 129   private static void checkInvalidInitialMaxHeapCombinations(String gcflag) throws Exception {
 130     expectError(new String[] { gcflag, "-XX:MaxHeapSize=4M", "-XX:InitialHeapSize=8M", "-version" });
 131     expectError(new String[] { gcflag, "-XX:InitialHeapSize=8M", "-XX:MaxHeapSize=4M", "-version" });
 132   }
 133 
 134   private static void checkValidInitialMaxHeapCombinations(String gcflag) throws Exception {
 135     expectValid(new String[] { gcflag, "-XX:InitialHeapSize=4M", "-XX:MaxHeapSize=8M", "-version" });
 136     expectValid(new String[] { gcflag, "-XX:MaxHeapSize=8M", "-XX:InitialHeapSize=4M", "-version" });
 137     expectValid(new String[] { gcflag, "-XX:MaxHeapSize=4M", "-XX:InitialHeapSize=4M", "-version" });
 138     // a value of "0" for initial heap size means auto-detect
 139     expectValid(new String[] { gcflag, "-XX:MaxHeapSize=4M", "-XX:InitialHeapSize=0M", "-version" });
 140   }
 141 
 142   private static long valueAfter(String source, String match) {
 143     int start = source.indexOf(match) + match.length();
 144     String tail = source.substring(start).split(" ")[0];
 145     return Long.parseLong(tail);
 146   }
 147 
 148   private static void getMinInitialMaxHeap(String[] args, MinInitialMaxValues val) throws Exception {
 149     ArrayList<String> finalargs = new ArrayList<String>();
 150 
 151     String[] testVMopts = new String[] {
 152       "-Xbootclasspath/a:.",
 153       "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI",
 154       "-cp", System.getProperty("java.class.path"),
 155     };
 156     // System.getProperty("test.java.opts") is '' if no options is set,
 157     // we need to skip such a result
 158     String[] externalVMOpts = new String[0];
 159     if (System.getProperty("test.java.opts") != null && System.getProperty("test.java.opts").length() != 0) {
 160       externalVMOpts = System.getProperty("test.java.opts").split(" ");
 161     }
 162 
 163     finalargs.addAll(Arrays.asList(externalVMOpts));
 164     finalargs.addAll(Arrays.asList(args));
 165     finalargs.addAll(Arrays.asList(testVMopts));
 166     finalargs.add(ErgoArgsPrinter.class.getName());
 167 
 168     ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(finalargs.toArray(new String[0]));
 169     OutputAnalyzer output = new OutputAnalyzer(pb.start());
 170     output.shouldHaveExitValue(0);
 171 
 172     // the output we watch for has the following format:
 173     //
 174     // "Minimum heap X Initial heap Y Maximum heap Z Min alignment A Max Alignment B"
 175     //
 176     // where A, B, X, Y and Z are sizes in bytes.
 177     // Unfortunately there is no other way to retrieve the minimum heap size and
 178     // the alignments.
 179 
 180     Matcher m = Pattern.compile("Minimum heap \\d+ Initial heap \\d+ Maximum heap \\d+ Min alignment \\d+ Max alignment \\d+").
 181       matcher(output.getStdout());
 182     if (!m.find()) {
 183       throw new RuntimeException("Could not find heap size string.");
 184     }
 185 
 186     String match = m.group();
 187 
 188     // actual values
 189     val.minHeapSize = valueAfter(match, "Minimum heap ");
 190     val.initialHeapSize = valueAfter(match, "Initial heap ");
 191     val.maxHeapSize = valueAfter(match, "Maximum heap ");
 192     val.minAlignment = valueAfter(match, "Min alignment ");
 193     val.maxAlignment = valueAfter(match, "Max alignment ");
 194   }
 195 
 196   /**
 197    * Verify whether the VM automatically synchronizes minimum and initial heap size if only
 198    * one is given for the GC specified.
 199    */
 200   public static void checkErgonomics(String[] args, long[] newoldsize,
 201     long expectedMin, long expectedInitial) throws Exception {
 202 
 203     MinInitialMaxValues v = new MinInitialMaxValues();
 204     getMinInitialMaxHeap(args, v);
 205 
 206     if ((expectedMin != -1) && (align_up(expectedMin, v.minAlignment) != v.minHeapSize)) {
 207       throw new RuntimeException("Actual minimum heap size of " + v.minHeapSize +
 208         " differs from expected minimum heap size of " + expectedMin);
 209     }
 210 
 211     if ((expectedInitial != -1) && (align_up(expectedInitial, v.minAlignment) != v.initialHeapSize)) {
 212       throw new RuntimeException("Actual initial heap size of " + v.initialHeapSize +
 213         " differs from expected initial heap size of " + expectedInitial);
 214     }
 215 
 216     // always check the invariant min <= initial <= max heap size
 217     if (!(v.minHeapSize <= v.initialHeapSize && v.initialHeapSize <= v.maxHeapSize)) {
 218       throw new RuntimeException("Inconsistent min/initial/max heap sizes, they are " +
 219         v.minHeapSize + "/" + v.initialHeapSize + "/" + v.maxHeapSize);
 220     }
 221   }
 222 
 223   /**
 224    * Verify whether the VM respects the given maximum heap size in MB for the
 225    * GC specified.
 226    * @param gcflag The garbage collector to test as command line flag. E.g. -XX:+UseG1GC
 227    * @param maxHeapSize the maximum heap size to verify, in MB.
 228    */
 229   public static void checkGenMaxHeapSize(String gcflag, long maxHeapsize) throws Exception {
 230     final long K = 1024;
 231 
 232     MinInitialMaxValues v = new MinInitialMaxValues();
 233     getMinInitialMaxHeap(new String[] { gcflag, "-XX:MaxHeapSize=" + maxHeapsize + "M" }, v);
 234 
 235     long expectedHeapSize = align_up(maxHeapsize * K * K, v.maxAlignment);
 236     long actualHeapSize = v.maxHeapSize;
 237 
 238     if (actualHeapSize > expectedHeapSize) {
 239       throw new RuntimeException("Heap has " + actualHeapSize  +
 240         " bytes, expected to be less than " + expectedHeapSize);
 241     }
 242   }
 243 
 244   private static long getFlagValue(String flag, String where) {
 245     Matcher m = Pattern.compile(flag + "\\s+:?=\\s+\\d+").matcher(where);
 246     if (!m.find()) {
 247       throw new RuntimeException("Could not find value for flag " + flag + " in output string");
 248     }
 249     String match = m.group();
 250     return Long.parseLong(match.substring(match.lastIndexOf(" ") + 1, match.length()));
 251   }
 252 
 253   private static void shouldContainOrNot(OutputAnalyzer output, boolean contains, String message) throws Exception {
 254     if (contains) {
 255       output.shouldContain(message);
 256     } else {
 257       output.shouldNotContain(message);
 258     }
 259   }
 260 
 261   private static void expect(String[] flags, boolean hasWarning, boolean hasError, int errorcode) throws Exception {
 262     ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(flags);
 263     OutputAnalyzer output = new OutputAnalyzer(pb.start());
 264     shouldContainOrNot(output, hasWarning, "Warning");
 265     shouldContainOrNot(output, hasError, "Error");
 266     output.shouldHaveExitValue(errorcode);
 267   }
 268 
 269   private static void expectError(String[] flags) throws Exception {
 270     expect(flags, false, true, 1);
 271   }
 272 
 273   private static void expectValid(String[] flags) throws Exception {
 274     expect(flags, false, false, 0);
 275   }
 276 }
 277