1 /* 2 * Copyright (c) 2007, 2012, 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. 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 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package sun.launcher; 27 28 /* 29 * 30 * <p><b>This is NOT part of any API supported by Sun Microsystems. 31 * If you write code that depends on this, you do so at your own 32 * risk. This code and its internal interfaces are subject to change 33 * or deletion without notice.</b> 34 * 35 */ 36 37 /** 38 * A utility package for the java(1), javaw(1) launchers. 39 * The following are helper methods that the native launcher uses 40 * to perform checks etc. using JNI, see src/share/bin/java.c 41 */ 42 import java.io.File; 43 import java.io.IOException; 44 import java.io.PrintStream; 45 import java.io.UnsupportedEncodingException; 46 import java.lang.reflect.Method; 47 import java.lang.reflect.Modifier; 48 import java.math.BigDecimal; 49 import java.math.RoundingMode; 50 import java.nio.charset.Charset; 51 import java.nio.file.DirectoryStream; 52 import java.nio.file.Files; 53 import java.nio.file.Path; 54 import java.util.ResourceBundle; 55 import java.text.MessageFormat; 56 import java.util.ArrayList; 57 import java.util.Collections; 58 import java.util.Iterator; 59 import java.util.List; 60 import java.util.Locale; 61 import java.util.Locale.Category; 62 import java.util.Properties; 63 import java.util.Set; 64 import java.util.TreeSet; 65 import java.util.jar.Attributes; 66 import java.util.jar.JarFile; 67 import java.util.jar.Manifest; 68 69 public enum LauncherHelper { 70 INSTANCE; 71 private static final String MAIN_CLASS = "Main-Class"; 72 private static StringBuilder outBuf = new StringBuilder(); 73 74 private static final String INDENT = " "; 75 private static final String VM_SETTINGS = "VM settings:"; 76 private static final String PROP_SETTINGS = "Property settings:"; 77 private static final String LOCALE_SETTINGS = "Locale settings:"; 78 79 // sync with java.c and sun.misc.VM 80 private static final String diagprop = "sun.java.launcher.diag"; 81 final static boolean trace = sun.misc.VM.getSavedProperty(diagprop) != null; 82 83 private static final String defaultBundleName = 84 "sun.launcher.resources.launcher"; 85 private static class ResourceBundleHolder { 86 private static final ResourceBundle RB = 87 ResourceBundle.getBundle(defaultBundleName); 88 } 89 private static PrintStream ostream; 90 private static final ClassLoader scloader = ClassLoader.getSystemClassLoader(); 91 private static Class<?> appClass; // application class, for GUI/reporting purposes 92 93 /* 94 * A method called by the launcher to print out the standard settings, 95 * by default -XshowSettings is equivalent to -XshowSettings:all, 96 * Specific information may be gotten by using suboptions with possible 97 * values vm, properties and locale. 98 * 99 * printToStderr: choose between stdout and stderr 100 * 101 * optionFlag: specifies which options to print default is all other 102 * possible values are vm, properties, locale. 103 * 104 * initialHeapSize: in bytes, as set by the launcher, a zero-value indicates 105 * this code should determine this value, using a suitable method or 106 * the line could be omitted. 107 * 108 * maxHeapSize: in bytes, as set by the launcher, a zero-value indicates 109 * this code should determine this value, using a suitable method. 110 * 111 * stackSize: in bytes, as set by the launcher, a zero-value indicates 112 * this code determine this value, using a suitable method or omit the 113 * line entirely. 114 */ 115 static void showSettings(boolean printToStderr, String optionFlag, 116 long initialHeapSize, long maxHeapSize, long stackSize, 117 boolean isServer) { 118 119 initOutput(printToStderr); 120 String opts[] = optionFlag.split(":"); 121 String optStr = (opts.length > 1 && opts[1] != null) 122 ? opts[1].trim() 123 : "all"; 124 switch (optStr) { 125 case "vm": 126 printVmSettings(initialHeapSize, maxHeapSize, 127 stackSize, isServer); 128 break; 129 case "properties": 130 printProperties(); 131 break; 132 case "locale": 133 printLocale(); 134 break; 135 default: 136 printVmSettings(initialHeapSize, maxHeapSize, stackSize, 137 isServer); 138 printProperties(); 139 printLocale(); 140 break; 141 } 142 } 143 144 /* 145 * prints the main vm settings subopt/section 146 */ 147 private static void printVmSettings( 148 long initialHeapSize, long maxHeapSize, 149 long stackSize, boolean isServer) { 150 151 ostream.println(VM_SETTINGS); 152 if (stackSize != 0L) { 153 ostream.println(INDENT + "Stack Size: " + 154 SizePrefix.scaleValue(stackSize)); 155 } 156 if (initialHeapSize != 0L) { 157 ostream.println(INDENT + "Min. Heap Size: " + 158 SizePrefix.scaleValue(initialHeapSize)); 159 } 160 if (maxHeapSize != 0L) { 161 ostream.println(INDENT + "Max. Heap Size: " + 162 SizePrefix.scaleValue(maxHeapSize)); 163 } else { 164 ostream.println(INDENT + "Max. Heap Size (Estimated): " 165 + SizePrefix.scaleValue(Runtime.getRuntime().maxMemory())); 166 } 167 ostream.println(INDENT + "Ergonomics Machine Class: " 168 + ((isServer) ? "server" : "client")); 169 ostream.println(INDENT + "Using VM: " 170 + System.getProperty("java.vm.name")); 171 ostream.println(); 172 } 173 174 /* 175 * prints the properties subopt/section 176 */ 177 private static void printProperties() { 178 Properties p = System.getProperties(); 179 ostream.println(PROP_SETTINGS); 180 List<String> sortedPropertyKeys = new ArrayList<>(); 181 sortedPropertyKeys.addAll(p.stringPropertyNames()); 182 Collections.sort(sortedPropertyKeys); 183 for (String x : sortedPropertyKeys) { 184 printPropertyValue(x, p.getProperty(x)); 185 } 186 ostream.println(); 187 } 188 189 private static boolean isPath(String key) { 190 return key.endsWith(".dirs") || key.endsWith(".path"); 191 } 192 193 private static void printPropertyValue(String key, String value) { 194 ostream.print(INDENT + key + " = "); 195 if (key.equals("line.separator")) { 196 for (byte b : value.getBytes()) { 197 switch (b) { 198 case 0xd: 199 ostream.print("\\r "); 200 break; 201 case 0xa: 202 ostream.print("\\n "); 203 break; 204 default: 205 // print any bizzare line separators in hex, but really 206 // shouldn't happen. 207 ostream.printf("0x%02X", b & 0xff); 208 break; 209 } 210 } 211 ostream.println(); 212 return; 213 } 214 if (!isPath(key)) { 215 ostream.println(value); 216 return; 217 } 218 String[] values = value.split(System.getProperty("path.separator")); 219 boolean first = true; 220 for (String s : values) { 221 if (first) { // first line treated specially 222 ostream.println(s); 223 first = false; 224 } else { // following lines prefix with indents 225 ostream.println(INDENT + INDENT + s); 226 } 227 } 228 } 229 230 /* 231 * prints the locale subopt/section 232 */ 233 private static void printLocale() { 234 Locale locale = Locale.getDefault(); 235 ostream.println(LOCALE_SETTINGS); 236 ostream.println(INDENT + "default locale = " + 237 locale.getDisplayLanguage()); 238 ostream.println(INDENT + "default display locale = " + 239 Locale.getDefault(Category.DISPLAY).getDisplayName()); 240 ostream.println(INDENT + "default format locale = " + 241 Locale.getDefault(Category.FORMAT).getDisplayName()); 242 printLocales(); 243 ostream.println(); 244 } 245 246 private static void printLocales() { 247 Locale[] tlocales = Locale.getAvailableLocales(); 248 final int len = tlocales == null ? 0 : tlocales.length; 249 if (len < 1 ) { 250 return; 251 } 252 // Locale does not implement Comparable so we convert it to String 253 // and sort it for pretty printing. 254 Set<String> sortedSet = new TreeSet<>(); 255 for (Locale l : tlocales) { 256 sortedSet.add(l.toString()); 257 } 258 259 ostream.print(INDENT + "available locales = "); 260 Iterator<String> iter = sortedSet.iterator(); 261 final int last = len - 1; 262 for (int i = 0 ; iter.hasNext() ; i++) { 263 String s = iter.next(); 264 ostream.print(s); 265 if (i != last) { 266 ostream.print(", "); 267 } 268 // print columns of 8 269 if ((i + 1) % 8 == 0) { 270 ostream.println(); 271 ostream.print(INDENT + INDENT); 272 } 273 } 274 } 275 276 private enum SizePrefix { 277 278 KILO(1024, "K"), 279 MEGA(1024 * 1024, "M"), 280 GIGA(1024 * 1024 * 1024, "G"), 281 TERA(1024L * 1024L * 1024L * 1024L, "T"); 282 long size; 283 String abbrev; 284 285 SizePrefix(long size, String abbrev) { 286 this.size = size; 287 this.abbrev = abbrev; 288 } 289 290 private static String scale(long v, SizePrefix prefix) { 291 return BigDecimal.valueOf(v).divide(BigDecimal.valueOf(prefix.size), 292 2, RoundingMode.HALF_EVEN).toPlainString() + prefix.abbrev; 293 } 294 /* 295 * scale the incoming values to a human readable form, represented as 296 * K, M, G and T, see java.c parse_size for the scaled values and 297 * suffixes. The lowest possible scaled value is Kilo. 298 */ 299 static String scaleValue(long v) { 300 if (v < MEGA.size) { 301 return scale(v, KILO); 302 } else if (v < GIGA.size) { 303 return scale(v, MEGA); 304 } else if (v < TERA.size) { 305 return scale(v, GIGA); 306 } else { 307 return scale(v, TERA); 308 } 309 } 310 } 311 312 /** 313 * A private helper method to get a localized message and also 314 * apply any arguments that we might pass. 315 */ 316 private static String getLocalizedMessage(String key, Object... args) { 317 String msg = ResourceBundleHolder.RB.getString(key); 318 return (args != null) ? MessageFormat.format(msg, args) : msg; 319 } 320 321 /** 322 * The java -help message is split into 3 parts, an invariant, followed 323 * by a set of platform dependent variant messages, finally an invariant 324 * set of lines. 325 * This method initializes the help message for the first time, and also 326 * assembles the invariant header part of the message. 327 */ 328 static void initHelpMessage(String progname) { 329 outBuf = outBuf.append(getLocalizedMessage("java.launcher.opt.header", 330 (progname == null) ? "java" : progname )); 331 outBuf = outBuf.append(getLocalizedMessage("java.launcher.opt.datamodel", 332 32)); 333 outBuf = outBuf.append(getLocalizedMessage("java.launcher.opt.datamodel", 334 64)); 335 } 336 337 /** 338 * Appends the vm selection messages to the header, already created. 339 * initHelpSystem must already be called. 340 */ 341 static void appendVmSelectMessage(String vm1, String vm2) { 342 outBuf = outBuf.append(getLocalizedMessage("java.launcher.opt.vmselect", 343 vm1, vm2)); 344 } 345 346 /** 347 * Appends the vm synoym message to the header, already created. 348 * initHelpSystem must be called before using this method. 349 */ 350 static void appendVmSynonymMessage(String vm1, String vm2) { 351 outBuf = outBuf.append(getLocalizedMessage("java.launcher.opt.hotspot", 352 vm1, vm2)); 353 } 354 355 /** 356 * Appends the vm Ergo message to the header, already created. 357 * initHelpSystem must be called before using this method. 358 */ 359 static void appendVmErgoMessage(boolean isServerClass, String vm) { 360 outBuf = outBuf.append(getLocalizedMessage("java.launcher.ergo.message1", 361 vm)); 362 outBuf = (isServerClass) 363 ? outBuf.append(",\n" + 364 getLocalizedMessage("java.launcher.ergo.message2") + "\n\n") 365 : outBuf.append(".\n\n"); 366 } 367 368 /** 369 * Appends the last invariant part to the previously created messages, 370 * and finishes up the printing to the desired output stream. 371 * initHelpSystem must be called before using this method. 372 */ 373 static void printHelpMessage(boolean printToStderr) { 374 initOutput(printToStderr); 375 outBuf = outBuf.append(getLocalizedMessage("java.launcher.opt.footer", 376 File.pathSeparator)); 377 ostream.println(outBuf.toString()); 378 } 379 380 /** 381 * Prints the Xusage text to the desired output stream. 382 */ 383 static void printXUsageMessage(boolean printToStderr) { 384 initOutput(printToStderr); 385 ostream.println(getLocalizedMessage("java.launcher.X.usage", 386 File.pathSeparator)); 387 if (System.getProperty("os.name").contains("OS X")) { 388 ostream.println(getLocalizedMessage("java.launcher.X.macosx.usage", 389 File.pathSeparator)); 390 } 391 } 392 393 static void initOutput(boolean printToStderr) { 394 ostream = (printToStderr) ? System.err : System.out; 395 } 396 397 static String getMainClassFromJar(String jarname) { 398 String mainValue = null; 399 try (JarFile jarFile = new JarFile(jarname)) { 400 Manifest manifest = jarFile.getManifest(); 401 if (manifest == null) { 402 abort(null, "java.launcher.jar.error2", jarname); 403 } 404 Attributes mainAttrs = manifest.getMainAttributes(); 405 if (mainAttrs == null) { 406 abort(null, "java.launcher.jar.error3", jarname); 407 } 408 mainValue = mainAttrs.getValue(MAIN_CLASS); 409 if (mainValue == null) { 410 abort(null, "java.launcher.jar.error3", jarname); 411 } 412 return mainValue.trim(); 413 } catch (IOException ioe) { 414 abort(ioe, "java.launcher.jar.error1", jarname); 415 } 416 return null; 417 } 418 419 // From src/share/bin/java.c: 420 // enum LaunchMode { LM_UNKNOWN = 0, LM_CLASS, LM_JAR }; 421 422 private static final int LM_UNKNOWN = 0; 423 private static final int LM_CLASS = 1; 424 private static final int LM_JAR = 2; 425 426 static void abort(Throwable t, String msgKey, Object... args) { 427 if (msgKey != null) { 428 ostream.println(getLocalizedMessage(msgKey, args)); 429 } 430 if (trace) { 431 if (t != null) { 432 t.printStackTrace(); 433 } else { 434 Thread.dumpStack(); 435 } 436 } 437 System.exit(1); 438 } 439 440 /** 441 * This method does the following: 442 * 1. gets the classname from a Jar's manifest, if necessary 443 * 2. loads the class using the System ClassLoader 444 * 3. ensures the availability and accessibility of the main method, 445 * using signatureDiagnostic method. 446 * a. does the class exist 447 * b. is there a main 448 * c. is the main public 449 * d. is the main static 450 * e. does the main take a String array for args 451 * 4. if no main method and if the class extends FX Application, then call 452 * on FXHelper to determine the main class to launch 453 * 5. and off we go...... 454 * 455 * @param printToStderr if set, all output will be routed to stderr 456 * @param mode LaunchMode as determined by the arguments passed on the 457 * command line 458 * @param what either the jar file to launch or the main class when using 459 * LM_CLASS mode 460 * @return the application's main class 461 */ 462 public static Class<?> checkAndLoadMain(boolean printToStderr, 463 int mode, 464 String what) { 465 initOutput(printToStderr); 466 // get the class name 467 String cn = null; 468 switch (mode) { 469 case LM_CLASS: 470 cn = what; 471 break; 472 case LM_JAR: 473 cn = getMainClassFromJar(what); 474 break; 475 default: 476 // should never happen 477 throw new InternalError("" + mode + ": Unknown launch mode"); 478 } 479 cn = cn.replace('/', '.'); 480 Class<?> mainClass = null; 481 try { 482 mainClass = scloader.loadClass(cn); 483 } catch (NoClassDefFoundError | ClassNotFoundException cnfe) { 484 abort(cnfe, "java.launcher.cls.error1", cn); 485 } 486 // set to mainClass, FXHelper may return something else 487 appClass = mainClass; 488 489 Method m = getMainMethod(mainClass); 490 if (m != null) { 491 // this will abort if main method has the wrong signature 492 validateMainMethod(m); 493 return mainClass; 494 } 495 496 // Check if FXHelper can launch it using the FX launcher 497 Class<?> fxClass = FXHelper.getFXMainClass(mainClass); 498 if (fxClass != null) { 499 return fxClass; 500 } 501 502 // not an FX application either, abort with an error 503 abort(null, "java.launcher.cls.error4", mainClass.getName(), 504 FXHelper.JAVAFX_APPLICATION_CLASS_NAME); 505 return null; // avoid compiler error... 506 } 507 508 /* 509 * Accessor method called by the launcher after getting the main class via 510 * checkAndLoadMain(). The "application class" is the class that is finally 511 * executed to start the application and in this case is used to report 512 * the correct application name, typically for UI purposes. 513 */ 514 public static Class<?> getApplicationClass() { 515 return appClass; 516 } 517 518 // Check for main method or return null if not found 519 static Method getMainMethod(Class<?> clazz) { 520 try { 521 return clazz.getMethod("main", String[].class); 522 } catch (NoSuchMethodException nsme) {} 523 return null; 524 } 525 526 // Check the signature of main and abort if it's incorrect 527 static void validateMainMethod(Method mainMethod) { 528 /* 529 * getMethod (above) will choose the correct method, based 530 * on its name and parameter type, however, we still have to 531 * ensure that the method is static and returns a void. 532 */ 533 int mod = mainMethod.getModifiers(); 534 if (!Modifier.isStatic(mod)) { 535 abort(null, "java.launcher.cls.error2", "static", 536 mainMethod.getDeclaringClass().getName()); 537 } 538 if (mainMethod.getReturnType() != java.lang.Void.TYPE) { 539 abort(null, "java.launcher.cls.error3", 540 mainMethod.getDeclaringClass().getName()); 541 } 542 } 543 544 private static final String encprop = "sun.jnu.encoding"; 545 private static String encoding = null; 546 private static boolean isCharsetSupported = false; 547 548 /* 549 * converts a c or a byte array to a platform specific string, 550 * previously implemented as a native method in the launcher. 551 */ 552 static String makePlatformString(boolean printToStderr, byte[] inArray) { 553 initOutput(printToStderr); 554 if (encoding == null) { 555 encoding = System.getProperty(encprop); 556 isCharsetSupported = Charset.isSupported(encoding); 557 } 558 try { 559 String out = isCharsetSupported 560 ? new String(inArray, encoding) 561 : new String(inArray); 562 return out; 563 } catch (UnsupportedEncodingException uee) { 564 abort(uee, null); 565 } 566 return null; // keep the compiler happy 567 } 568 569 static String[] expandArgs(String[] argArray) { 570 List<StdArg> aList = new ArrayList<>(); 571 for (String x : argArray) { 572 aList.add(new StdArg(x)); 573 } 574 return expandArgs(aList); 575 } 576 577 static String[] expandArgs(List<StdArg> argList) { 578 ArrayList<String> out = new ArrayList<>(); 579 if (trace) { 580 System.err.println("Incoming arguments:"); 581 } 582 for (StdArg a : argList) { 583 if (trace) { 584 System.err.println(a); 585 } 586 if (a.needsExpansion) { 587 File x = new File(a.arg); 588 File parent = x.getParentFile(); 589 String glob = x.getName(); 590 if (parent == null) { 591 parent = new File("."); 592 } 593 try (DirectoryStream<Path> dstream = 594 Files.newDirectoryStream(parent.toPath(), glob)) { 595 int entries = 0; 596 for (Path p : dstream) { 597 out.add(p.normalize().toString()); 598 entries++; 599 } 600 if (entries == 0) { 601 out.add(a.arg); 602 } 603 } catch (Exception e) { 604 out.add(a.arg); 605 if (trace) { 606 System.err.println("Warning: passing argument as-is " + a); 607 System.err.print(e); 608 } 609 } 610 } else { 611 out.add(a.arg); 612 } 613 } 614 String[] oarray = new String[out.size()]; 615 out.toArray(oarray); 616 617 if (trace) { 618 System.err.println("Expanded arguments:"); 619 for (String x : oarray) { 620 System.err.println(x); 621 } 622 } 623 return oarray; 624 } 625 626 /* duplicate of the native StdArg struct */ 627 private static class StdArg { 628 final String arg; 629 final boolean needsExpansion; 630 StdArg(String arg, boolean expand) { 631 this.arg = arg; 632 this.needsExpansion = expand; 633 } 634 // protocol: first char indicates whether expansion is required 635 // 'T' = true ; needs expansion 636 // 'F' = false; needs no expansion 637 StdArg(String in) { 638 this.arg = in.substring(1); 639 needsExpansion = in.charAt(0) == 'T'; 640 } 641 public String toString() { 642 return "StdArg{" + "arg=" + arg + ", needsExpansion=" + needsExpansion + '}'; 643 } 644 } 645 646 static final class FXHelper { 647 private static final String JAVAFX_APPLICATION_CLASS_NAME = 648 "javafx.application.Application"; 649 private static final String JAVAFX_LAUNCHER_CLASS_NAME = 650 "com.sun.javafx.application.LauncherImpl"; 651 652 /* 653 * FX application launcher and launch method, so we can launch 654 * applications with no main method. 655 */ 656 private static Class<?> fxLauncherClass = null; 657 private static Method fxLauncherMethod = null; 658 659 /* 660 * We can assume that the class does NOT have a main method or it would 661 * have been handled already. We do, however, need to check if the class 662 * extends Application and the launcher is available and abort with an 663 * error if it's not. 664 */ 665 private static Class<?> getFXMainClass(Class<?> mainClass) { 666 // Check if mainClass extends Application 667 if (!doesExtendFXApplication(mainClass)) { 668 return null; 669 } 670 671 // Check for the FX launcher classes 672 try { 673 fxLauncherClass = scloader.loadClass(JAVAFX_LAUNCHER_CLASS_NAME); 674 fxLauncherMethod = fxLauncherClass.getMethod("launchApplication", 675 Class.class, String[].class); 676 } catch (ClassNotFoundException | NoSuchMethodException ex) { 677 abort(ex, "java.launcher.cls.error5", ex); 678 } 679 680 // That's all, return this class so we can launch later 681 return FXHelper.class; 682 } 683 684 /* 685 * Check if the given class is a JavaFX Application class. This is done 686 * in a way that does not cause the Application class to load or throw 687 * ClassNotFoundException if the JavaFX runtime is not available. 688 */ 689 private static boolean doesExtendFXApplication(Class<?> mainClass) { 690 for (Class<?> sc = mainClass.getSuperclass(); sc != null; 691 sc = sc.getSuperclass()) { 692 if (sc.getName().equals(JAVAFX_APPLICATION_CLASS_NAME)) { 693 return true; 694 } 695 } 696 return false; 697 } 698 699 // preloader ? 700 public static void main(String... args) throws Exception { 701 // launch appClass via fxLauncherMethod 702 fxLauncherMethod.invoke(null, new Object[] {appClass, args}); 703 } 704 } 705 } 706