LauncherHelper.java 17.9 KB
Newer Older
1
/*
2
 * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
 */

package sun.launcher;

/*
 *
 *  <p><b>This is NOT part of any API supported by Sun Microsystems.
 *  If you write code that depends on this, you do so at your own
 *  risk.  This code and its internal interfaces are subject to change
 *  or deletion without notice.</b>
 *
 */

/**
 * A utility package for the java(1), javaw(1) launchers.
 * The following are helper methods that the native launcher uses
 * to perform checks etc. using JNI, see src/share/bin/java.c
 */
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
47 48
import java.math.BigDecimal;
import java.math.RoundingMode;
49 50
import java.util.ResourceBundle;
import java.text.MessageFormat;
51 52
import java.util.ArrayList;
import java.util.Collections;
K
ksrini 已提交
53
import java.util.Iterator;
54 55
import java.util.List;
import java.util.Locale;
K
ksrini 已提交
56
import java.util.Locale.Category;
57
import java.util.Properties;
K
ksrini 已提交
58 59
import java.util.Set;
import java.util.TreeSet;
60 61 62 63 64 65 66 67 68 69 70 71
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

public enum LauncherHelper {
    INSTANCE;
    private static final String defaultBundleName =
            "sun.launcher.resources.launcher";
    private static final String MAIN_CLASS = "Main-Class";

    private static StringBuilder outBuf = new StringBuilder();

72
    private static ResourceBundle javarb = null;
73 74 75 76 77 78

    private static final String INDENT = "    ";
    private static final String VM_SETTINGS     = "VM settings:";
    private static final String PROP_SETTINGS   = "Property settings:";
    private static final String LOCALE_SETTINGS = "Locale settings:";

79 80 81 82 83 84 85
    private static synchronized ResourceBundle getLauncherResourceBundle() {
        if (javarb == null) {
            javarb = ResourceBundle.getBundle(defaultBundleName);
        }
        return javarb;
    }

86 87 88 89 90 91 92 93 94 95 96
    /*
     * A method called by the launcher to print out the standard settings,
     * by default -XshowSettings is equivalent to -XshowSettings:all,
     * Specific information may be gotten by using suboptions with possible
     * values vm, properties and locale.
     *
     * printToStderr: choose between stdout and stderr
     *
     * optionFlag: specifies which options to print default is all other
     *    possible values are vm, properties, locale.
     *
K
ksrini 已提交
97 98 99 100
     * initialHeapSize: in bytes, as set by the launcher, a zero-value indicates
     *    this code should determine this value, using a suitable method or
     *    the line could be omitted.
     *
101 102 103 104
     * maxHeapSize: in bytes, as set by the launcher, a zero-value indicates
     *    this code should determine this value, using a suitable method.
     *
     * stackSize: in bytes, as set by the launcher, a zero-value indicates
K
ksrini 已提交
105 106
     *    this code determine this value, using a suitable method or omit the
     *    line entirely.
107 108
     */
    static void showSettings(boolean printToStderr, String optionFlag,
K
ksrini 已提交
109 110
            long initialHeapSize, long maxHeapSize, long stackSize,
            boolean isServer) {
111 112 113 114 115 116 117 118

        PrintStream ostream = (printToStderr) ? System.err : System.out;
        String opts[] = optionFlag.split(":");
        String optStr = (opts.length > 1 && opts[1] != null)
                ? opts[1].trim()
                : "all";
        switch (optStr) {
            case "vm":
K
ksrini 已提交
119 120
                printVmSettings(ostream, initialHeapSize, maxHeapSize,
                        stackSize, isServer);
121 122 123 124 125 126 127 128
                break;
            case "properties":
                printProperties(ostream);
                break;
            case "locale":
                printLocale(ostream);
                break;
            default:
K
ksrini 已提交
129 130
                printVmSettings(ostream, initialHeapSize, maxHeapSize,
                        stackSize, isServer);
131 132 133 134 135 136 137 138 139
                printProperties(ostream);
                printLocale(ostream);
                break;
        }
    }

    /*
     * prints the main vm settings subopt/section
     */
K
ksrini 已提交
140 141
    private static void printVmSettings(PrintStream ostream,
            long initialHeapSize, long maxHeapSize,
142 143 144 145
            long stackSize, boolean isServer) {

        ostream.println(VM_SETTINGS);
        if (stackSize != 0L) {
K
ksrini 已提交
146 147 148 149 150 151
            ostream.println(INDENT + "Stack Size: " +
                    SizePrefix.scaleValue(stackSize));
        }
        if (initialHeapSize != 0L) {
             ostream.println(INDENT + "Min. Heap Size: " +
                    SizePrefix.scaleValue(initialHeapSize));
152 153
        }
        if (maxHeapSize != 0L) {
K
ksrini 已提交
154 155
            ostream.println(INDENT + "Max. Heap Size: " +
                    SizePrefix.scaleValue(maxHeapSize));
156 157
        } else {
            ostream.println(INDENT + "Max. Heap Size (Estimated): "
K
ksrini 已提交
158
                    + SizePrefix.scaleValue(Runtime.getRuntime().maxMemory()));
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
        }
        ostream.println(INDENT + "Ergonomics Machine Class: "
                + ((isServer) ? "server" : "client"));
        ostream.println(INDENT + "Using VM: "
                + System.getProperty("java.vm.name"));
        ostream.println();
    }

    /*
     * prints the properties subopt/section
     */
    private static void printProperties(PrintStream ostream) {
        Properties p = System.getProperties();
        ostream.println(PROP_SETTINGS);
        List<String> sortedPropertyKeys = new ArrayList<>();
        sortedPropertyKeys.addAll(p.stringPropertyNames());
        Collections.sort(sortedPropertyKeys);
        for (String x : sortedPropertyKeys) {
            printPropertyValue(ostream, x, p.getProperty(x));
        }
        ostream.println();
    }

    private static boolean isPath(String key) {
        return key.endsWith(".dirs") || key.endsWith(".path");
    }

    private static void printPropertyValue(PrintStream ostream,
            String key, String value) {
        ostream.print(INDENT + key + " = ");
        if (key.equals("line.separator")) {
K
ksrini 已提交
190
            for (byte b : value.getBytes()) {
191 192
                switch (b) {
                    case 0xd:
K
ksrini 已提交
193
                        ostream.print("\\r ");
194 195
                        break;
                    case 0xa:
K
ksrini 已提交
196
                        ostream.print("\\n ");
197 198
                        break;
                    default:
K
ksrini 已提交
199 200
                        // print any bizzare line separators in hex, but really
                        // shouldn't happen.
201 202 203 204 205 206 207 208 209 210 211 212
                        ostream.printf("0x%02X", b & 0xff);
                        break;
                }
            }
            ostream.println();
            return;
        }
        if (!isPath(key)) {
            ostream.println(value);
            return;
        }
        String[] values = value.split(System.getProperty("path.separator"));
K
ksrini 已提交
213 214 215 216 217
        boolean first = true;
        for (String s : values) {
            if (first) { // first line treated specially
                ostream.println(s);
                first = false;
218
            } else { // following lines prefix with indents
K
ksrini 已提交
219
                ostream.println(INDENT + INDENT + s);
220 221 222 223 224 225 226 227 228 229
            }
        }
    }

    /*
     * prints the locale subopt/section
     */
    private static void printLocale(PrintStream ostream) {
        Locale locale = Locale.getDefault();
        ostream.println(LOCALE_SETTINGS);
K
ksrini 已提交
230 231 232 233 234 235
        ostream.println(INDENT + "default locale = " +
                locale.getDisplayLanguage());
        ostream.println(INDENT + "default display locale = " +
                Locale.getDefault(Category.DISPLAY).getDisplayName());
        ostream.println(INDENT + "default format locale = " +
                Locale.getDefault(Category.FORMAT).getDisplayName());
236 237 238 239 240
        printLocales(ostream);
        ostream.println();
    }

    private static void printLocales(PrintStream ostream) {
K
ksrini 已提交
241 242
        Locale[] tlocales = Locale.getAvailableLocales();
        final int len = tlocales == null ? 0 : tlocales.length;
243 244 245
        if (len < 1 ) {
            return;
        }
K
ksrini 已提交
246 247 248 249 250 251 252
        // Locale does not implement Comparable so we convert it to String
        // and sort it for pretty printing.
        Set<String> sortedSet = new TreeSet<>();
        for (Locale l : tlocales) {
            sortedSet.add(l.toString());
        }

253
        ostream.print(INDENT + "available locales = ");
K
ksrini 已提交
254 255 256 257 258
        Iterator<String> iter = sortedSet.iterator();
        final int last = len - 1;
        for (int i = 0 ; iter.hasNext() ; i++) {
            String s = iter.next();
            ostream.print(s);
259 260 261 262 263 264 265 266 267
            if (i != last) {
                ostream.print(", ");
            }
            // print columns of 8
            if ((i + 1) % 8 == 0) {
                ostream.println();
                ostream.print(INDENT + INDENT);
            }
        }
K
ksrini 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    }

    private enum SizePrefix {

        KILO(1024, "K"),
        MEGA(1024 * 1024, "M"),
        GIGA(1024 * 1024 * 1024, "G"),
        TERA(1024L * 1024L * 1024L * 1024L, "T");
        long size;
        String abbrev;

        SizePrefix(long size, String abbrev) {
            this.size = size;
            this.abbrev = abbrev;
        }

        private static String scale(long v, SizePrefix prefix) {
            return BigDecimal.valueOf(v).divide(BigDecimal.valueOf(prefix.size),
                    2, RoundingMode.HALF_EVEN).toPlainString() + prefix.abbrev;
        }
        /*
         * scale the incoming values to a human readable form, represented as
         * K, M, G and T, see java.c parse_size for the scaled values and
         * suffixes. The lowest possible scaled value is Kilo.
         */
        static String scaleValue(long v) {
            if (v < MEGA.size) {
                return scale(v, KILO);
            } else if (v < GIGA.size) {
                return scale(v, MEGA);
            } else if (v < TERA.size) {
                return scale(v, GIGA);
            } else {
                return scale(v, TERA);
            }
        }
304 305
    }

306 307 308 309 310
    /**
     * A private helper method to get a localized message and also
     * apply any arguments that we might pass.
     */
    private static String getLocalizedMessage(String key, Object... args) {
311
        String msg = getLauncherResourceBundle().getString(key);
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
        return (args != null) ? MessageFormat.format(msg, args) : msg;
    }

    /**
     * The java -help message is split into 3 parts, an invariant, followed
     * by a set of platform dependent variant messages, finally an invariant
     * set of lines.
     * This method initializes the help message for the first time, and also
     * assembles the invariant header part of the message.
     */
    static void initHelpMessage(String progname) {
        outBuf = outBuf.append(getLocalizedMessage("java.launcher.opt.header",
                (progname == null) ? "java" : progname ));
        outBuf = outBuf.append(getLocalizedMessage("java.launcher.opt.datamodel",
                32));
        outBuf = outBuf.append(getLocalizedMessage("java.launcher.opt.datamodel",
                64));
    }

    /**
     * Appends the vm selection messages to the header, already created.
     * initHelpSystem must already be called.
     */
    static void appendVmSelectMessage(String vm1, String vm2) {
        outBuf = outBuf.append(getLocalizedMessage("java.launcher.opt.vmselect",
                vm1, vm2));
    }

    /**
     * Appends the vm synoym message to the header, already created.
     * initHelpSystem must be called before using this method.
     */
    static void appendVmSynonymMessage(String vm1, String vm2) {
        outBuf = outBuf.append(getLocalizedMessage("java.launcher.opt.hotspot",
                vm1, vm2));
    }

    /**
     * Appends the vm Ergo message to the header, already created.
     * initHelpSystem must be called before using this method.
     */
    static void appendVmErgoMessage(boolean isServerClass, String vm) {
        outBuf = outBuf.append(getLocalizedMessage("java.launcher.ergo.message1",
                vm));
        outBuf = (isServerClass)
             ? outBuf.append(",\n" +
                getLocalizedMessage("java.launcher.ergo.message2") + "\n\n")
             : outBuf.append(".\n\n");
    }

    /**
     * Appends the last invariant part to the previously created messages,
     * and finishes up the printing to the desired output stream.
     * initHelpSystem must be called before using this method.
     */
    static void printHelpMessage(boolean printToStderr) {
        PrintStream ostream = (printToStderr) ? System.err : System.out;
        outBuf = outBuf.append(getLocalizedMessage("java.launcher.opt.footer",
                File.pathSeparator));
        ostream.println(outBuf.toString());
    }

    /**
     * Prints the Xusage text to the desired output stream.
     */
    static void printXUsageMessage(boolean printToStderr) {
        PrintStream ostream =  (printToStderr) ? System.err : System.out;
        ostream.println(getLocalizedMessage("java.launcher.X.usage",
                File.pathSeparator));
    }

    static String getMainClassFromJar(String jarname) throws IOException {
        JarFile jarFile = null;
        try {
            jarFile = new JarFile(jarname);
            Manifest manifest = jarFile.getManifest();
            if (manifest == null) {
                throw new IOException("manifest not found in " + jarname);
            }
            Attributes mainAttrs = manifest.getMainAttributes();
            if (mainAttrs == null) {
                throw new IOException("no main mainifest attributes, in " +
                        jarname);
            }
396
            return mainAttrs.getValue(MAIN_CLASS).trim();
397 398 399 400 401 402 403
        } finally {
            if (jarFile != null) {
                jarFile.close();
            }
        }
    }

404 405 406 407 408 409 410 411

    // From src/share/bin/java.c:
    //   enum LaunchMode { LM_UNKNOWN = 0, LM_CLASS, LM_JAR };

    private static final int LM_UNKNOWN = 0;
    private static final int LM_CLASS   = 1;
    private static final int LM_JAR     = 2;

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    /**
     * This method does the following:
     * 1. gets the classname from a Jar's manifest, if necessary
     * 2. loads the class using the System ClassLoader
     * 3. ensures the availability and accessibility of the main method,
     *    using signatureDiagnostic method.
     *    a. does the class exist
     *    b. is there a main
     *    c. is the main public
     *    d. is the main static
     *    c. does the main take a String array for args
     * 4. and off we go......
     *
     * @param printToStderr
     * @param isJar
     * @param name
     * @return
429
     * @throws java.io.IOException
430
     */
431 432 433 434 435 436 437
    public static Class<?> checkAndLoadMain(boolean printToStderr,
                                            int mode,
                                            String what) throws IOException
    {

        ClassLoader ld = ClassLoader.getSystemClassLoader();

438
        // get the class name
439 440 441 442 443 444 445 446 447 448 449 450 451
        String cn = null;
        switch (mode) {
        case LM_CLASS:
            cn = what;
            break;
        case LM_JAR:
            cn = getMainClassFromJar(what);
            break;
        default:
            throw new InternalError("" + mode + ": Unknown launch mode");
        }
        cn = cn.replace('/', '.');

452
        PrintStream ostream = (printToStderr) ? System.err : System.out;
453
        Class<?> c = null;
454
        try {
455
            c = ld.loadClass(cn);
456
        } catch (ClassNotFoundException cnfe) {
457 458 459
            ostream.println(getLocalizedMessage("java.launcher.cls.error1",
                                                cn));
            NoClassDefFoundError ncdfe = new NoClassDefFoundError(cn);
460 461
            ncdfe.initCause(cnfe);
            throw ncdfe;
462
        }
463 464
        signatureDiagnostic(ostream, c);
        return c;
465 466 467 468 469 470 471
    }

    static void signatureDiagnostic(PrintStream ostream, Class<?> clazz) {
        String classname = clazz.getName();
        Method method = null;
        try {
            method = clazz.getMethod("main", String[].class);
472
        } catch (NoSuchMethodException nsme) {
473 474 475 476 477
            ostream.println(getLocalizedMessage("java.launcher.cls.error4",
                    classname));
            throw new RuntimeException("Main method not found in " + classname);
        }
        /*
478 479 480
         * getMethod (above) will choose the correct method, based
         * on its name and parameter type, however, we still have to
         * ensure that the method is static and returns a void.
481 482 483 484 485 486 487 488
         */
        int mod = method.getModifiers();
        if (!Modifier.isStatic(mod)) {
            ostream.println(getLocalizedMessage("java.launcher.cls.error2",
                    "static", classname));
            throw new RuntimeException("Main method is not static in class " +
                    classname);
        }
489
        if (method.getReturnType() != java.lang.Void.TYPE) {
490 491 492 493 494 495 496 497 498
            ostream.println(getLocalizedMessage("java.launcher.cls.error3",
                    classname));
            throw new RuntimeException("Main method must return a value" +
                    " of type void in class " +
                    classname);
        }
        return;
    }
}