1 /*
   2  * Copyright (c) 2014, 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 package jdk.vm.ci.options;
  24 
  25 import static jdk.vm.ci.inittimer.InitTimer.*;
  26 
  27 import java.io.*;
  28 import java.util.*;
  29 
  30 import jdk.vm.ci.inittimer.*;
  31 
  32 /**
  33  * This class contains methods for parsing JVMCI options and matching them against a set of
  34  * {@link OptionDescriptors}. The {@link OptionDescriptors} are loaded from JVMCI jars, either
  35  * {@linkplain JVMCIJarsOptionDescriptorsProvider directly} or via a {@link ServiceLoader}.
  36  */
  37 public class OptionsParser {
  38 
  39     private static final OptionValue<Boolean> PrintFlags = new OptionValue<>(false);
  40 
  41     /**
  42      * A service for looking up {@link OptionDescriptor}s.
  43      */
  44     public interface OptionDescriptorsProvider {
  45         /**
  46          * Gets the {@link OptionDescriptor} matching a given option {@linkplain Option#name() name}
  47          * or null if no option of that name is provided by this object.
  48          */
  49         OptionDescriptor get(String name);
  50     }
  51 
  52     public interface OptionConsumer {
  53         void set(OptionDescriptor desc, Object value);
  54     }
  55 
  56     /**
  57      * Parses the options in {@code <jre>/lib/jvmci/options} if {@code parseOptionsFile == true} and
  58      * the file exists followed by the JVMCI options in {@code options} if {@code options != null}.
  59      *
  60      * Called from VM. This method has an object return type to allow it to be called with a VM
  61      * utility function used to call other static initialization methods.
  62      *
  63      * @param options JVMCI options as serialized (name, value) pairs
  64      * @param parseOptionsFile specifies whether to look for and parse
  65      *            {@code <jre>/lib/jvmci/options}
  66      */
  67     @SuppressWarnings("try")
  68     public static Boolean parseOptionsFromVM(String[] options, boolean parseOptionsFile) {
  69         try (InitTimer t = timer("ParseOptions")) {
  70             JVMCIJarsOptionDescriptorsProvider odp = new JVMCIJarsOptionDescriptorsProvider();
  71 
  72             if (parseOptionsFile) {
  73                 File javaHome = new File(System.getProperty("java.home"));
  74                 File lib = new File(javaHome, "lib");
  75                 File jvmci = new File(lib, "jvmci");
  76                 File jvmciOptions = new File(jvmci, "options");
  77                 if (jvmciOptions.exists()) {
  78                     try (BufferedReader br = new BufferedReader(new FileReader(jvmciOptions))) {
  79                         String optionSetting = null;
  80                         int lineNo = 1;
  81                         while ((optionSetting = br.readLine()) != null) {
  82                             if (!optionSetting.isEmpty() && optionSetting.charAt(0) != '#') {
  83                                 try {
  84                                     parseOptionSetting(optionSetting, null, odp);
  85                                 } catch (Throwable e) {
  86                                     throw new InternalError("Error parsing " + jvmciOptions + ", line " + lineNo, e);
  87                                 }
  88                             }
  89                             lineNo++;
  90                         }
  91                     } catch (IOException e) {
  92                         throw new InternalError("Error reading " + jvmciOptions, e);
  93                     }
  94                 }
  95             }
  96 
  97             if (options != null) {
  98                 assert options.length % 2 == 0;
  99                 for (int i = 0; i < options.length / 2; i++) {
 100                     String name = options[i * 2];
 101                     String value = options[i * 2 + 1];
 102                     parseOption(OptionsLoader.options, name, value, null, odp);
 103                 }
 104             }
 105         }
 106         return Boolean.TRUE;
 107     }
 108 
 109     /**
 110      * Parses a given option setting.
 111      *
 112      * @param optionSetting a string matching the pattern {@code <name>=<value>}
 113      * @param setter the object to notify of the parsed option and value
 114      */
 115     public static void parseOptionSetting(String optionSetting, OptionConsumer setter, OptionDescriptorsProvider odp) {
 116         int eqIndex = optionSetting.indexOf('=');
 117         if (eqIndex == -1) {
 118             throw new InternalError("Option setting has does not match the pattern <name>=<value>: " + optionSetting);
 119         }
 120         String name = optionSetting.substring(0, eqIndex);
 121         String value = optionSetting.substring(eqIndex + 1);
 122         parseOption(OptionsLoader.options, name, value, setter, odp);
 123     }
 124 
 125     /**
 126      * Parses a given option name and value.
 127      *
 128      * @param options
 129      * @param name the option name
 130      * @param valueString the option value as a string
 131      * @param setter the object to notify of the parsed option and value
 132      * @param odp
 133      *
 134      * @throws IllegalArgumentException if there's a problem parsing {@code option}
 135      */
 136     public static void parseOption(SortedMap<String, OptionDescriptor> options, String name, String valueString, OptionConsumer setter, OptionDescriptorsProvider odp) {
 137         OptionDescriptor desc = options.get(name);
 138         if (desc == null && odp != null) {
 139             desc = odp.get(name);
 140         }
 141         if (desc == null && name.equals("PrintFlags")) {
 142             desc = OptionDescriptor.create("PrintFlags", Boolean.class, "Prints all JVMCI flags and exits", OptionsParser.class, "PrintFlags", PrintFlags);
 143         }
 144         if (desc == null) {
 145             List<OptionDescriptor> matches = fuzzyMatch(options, name);
 146             Formatter msg = new Formatter();
 147             msg.format("Could not find option %s", name);
 148             if (!matches.isEmpty()) {
 149                 msg.format("%nDid you mean one of the following?");
 150                 for (OptionDescriptor match : matches) {
 151                     msg.format("%n    %s=<value>", match.getName());
 152                 }
 153             }
 154             throw new IllegalArgumentException(msg.toString());
 155         }
 156 
 157         Class<?> optionType = desc.getType();
 158         Object value;
 159         if (optionType == Boolean.class) {
 160             if ("true".equals(valueString)) {
 161                 value = Boolean.TRUE;
 162             } else if ("false".equals(valueString)) {
 163                 value = Boolean.FALSE;
 164             } else {
 165                 throw new IllegalArgumentException("Boolean option '" + name + "' must have value \"true\" or \"false\", not \"" + valueString + "\"");
 166             }
 167         } else if (optionType == Float.class) {
 168             value = Float.parseFloat(valueString);
 169         } else if (optionType == Double.class) {
 170             value = Double.parseDouble(valueString);
 171         } else if (optionType == Integer.class) {
 172             value = Integer.valueOf((int) parseLong(valueString));
 173         } else if (optionType == Long.class) {
 174             value = Long.valueOf(parseLong(valueString));
 175         } else if (optionType == String.class) {
 176             value = valueString;
 177         } else {
 178             throw new IllegalArgumentException("Wrong value for option '" + name + "'");
 179         }
 180         if (setter == null) {
 181             desc.getOptionValue().setValue(value);
 182         } else {
 183             setter.set(desc, value);
 184         }
 185 
 186         if (PrintFlags.getValue()) {
 187             printFlags(options, "JVMCI", System.out);
 188             System.exit(0);
 189         }
 190     }
 191 
 192     private static long parseLong(String v) {
 193         String valueString = v.toLowerCase();
 194         long scale = 1;
 195         if (valueString.endsWith("k")) {
 196             scale = 1024L;
 197         } else if (valueString.endsWith("m")) {
 198             scale = 1024L * 1024L;
 199         } else if (valueString.endsWith("g")) {
 200             scale = 1024L * 1024L * 1024L;
 201         } else if (valueString.endsWith("t")) {
 202             scale = 1024L * 1024L * 1024L * 1024L;
 203         }
 204 
 205         if (scale != 1) {
 206             /* Remove trailing scale character. */
 207             valueString = valueString.substring(0, valueString.length() - 1);
 208         }
 209 
 210         return Long.parseLong(valueString) * scale;
 211     }
 212 
 213     /**
 214      * Wraps some given text to one or more lines of a given maximum width.
 215      *
 216      * @param text text to wrap
 217      * @param width maximum width of an output line, exception for words in {@code text} longer than
 218      *            this value
 219      * @return {@code text} broken into lines
 220      */
 221     private static List<String> wrap(String text, int width) {
 222         List<String> lines = Collections.singletonList(text);
 223         if (text.length() > width) {
 224             String[] chunks = text.split("\\s+");
 225             lines = new ArrayList<>();
 226             StringBuilder line = new StringBuilder();
 227             for (String chunk : chunks) {
 228                 if (line.length() + chunk.length() > width) {
 229                     lines.add(line.toString());
 230                     line.setLength(0);
 231                 }
 232                 if (line.length() != 0) {
 233                     line.append(' ');
 234                 }
 235                 String[] embeddedLines = chunk.split("%n", -2);
 236                 if (embeddedLines.length == 1) {
 237                     line.append(chunk);
 238                 } else {
 239                     for (int i = 0; i < embeddedLines.length; i++) {
 240                         line.append(embeddedLines[i]);
 241                         if (i < embeddedLines.length - 1) {
 242                             lines.add(line.toString());
 243                             line.setLength(0);
 244                         }
 245                     }
 246                 }
 247             }
 248             if (line.length() != 0) {
 249                 lines.add(line.toString());
 250             }
 251         }
 252         return lines;
 253     }
 254 
 255     public static void printFlags(SortedMap<String, OptionDescriptor> sortedOptions, String prefix, PrintStream out) {
 256         out.println("[List of " + prefix + " options]");
 257         for (Map.Entry<String, OptionDescriptor> e : sortedOptions.entrySet()) {
 258             e.getKey();
 259             OptionDescriptor desc = e.getValue();
 260             Object value = desc.getOptionValue().getValue();
 261             List<String> helpLines = wrap(desc.getHelp(), 70);
 262             out.println(String.format("%9s %-40s = %-14s %s", desc.getType().getSimpleName(), e.getKey(), value, helpLines.get(0)));
 263             for (int i = 1; i < helpLines.size(); i++) {
 264                 out.println(String.format("%67s %s", " ", helpLines.get(i)));
 265             }
 266         }
 267     }
 268 
 269     /**
 270      * Compute string similarity based on Dice's coefficient.
 271      *
 272      * Ported from str_similar() in globals.cpp.
 273      */
 274     static float stringSimiliarity(String str1, String str2) {
 275         int hit = 0;
 276         for (int i = 0; i < str1.length() - 1; ++i) {
 277             for (int j = 0; j < str2.length() - 1; ++j) {
 278                 if ((str1.charAt(i) == str2.charAt(j)) && (str1.charAt(i + 1) == str2.charAt(j + 1))) {
 279                     ++hit;
 280                     break;
 281                 }
 282             }
 283         }
 284         return 2.0f * hit / (str1.length() + str2.length());
 285     }
 286 
 287     private static final float FUZZY_MATCH_THRESHOLD = 0.7F;
 288 
 289     /**
 290      * Returns the set of options that fuzzy match a given option name.
 291      */
 292     private static List<OptionDescriptor> fuzzyMatch(SortedMap<String, OptionDescriptor> options, String optionName) {
 293         List<OptionDescriptor> matches = new ArrayList<>();
 294         for (Map.Entry<String, OptionDescriptor> e : options.entrySet()) {
 295             float score = stringSimiliarity(e.getKey(), optionName);
 296             if (score >= FUZZY_MATCH_THRESHOLD) {
 297                 matches.add(e.getValue());
 298             }
 299         }
 300         return matches;
 301     }
 302 }