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