1 /*
   2  * Copyright (c) 2011, 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 apple.launcher;
  27 
  28 import java.io.*;
  29 import java.lang.reflect.*;
  30 import java.security.PrivilegedAction;
  31 import java.text.MessageFormat;
  32 import java.util.*;
  33 import java.util.jar.*;
  34 
  35 import javax.swing.*;
  36 
  37 class JavaAppLauncher implements Runnable {
  38     static {
  39         java.security.AccessController.doPrivileged((PrivilegedAction<?>)new sun.security.action.LoadLibraryAction("osx"));
  40     }
  41 
  42     private static native <T> T nativeConvertAndRelease(final long ptr);
  43     private static native void nativeInvokeNonPublic(Class<? extends Method> cls, Method m, String[] args);
  44 
  45     // entry point from native
  46     static void launch(final long javaDictionaryPtr, final boolean verbose) {
  47         final Map<String, ?> javaDictionary = nativeConvertAndRelease(javaDictionaryPtr);
  48         (new JavaAppLauncher(javaDictionary, verbose)).run();
  49     }
  50 
  51         // these are the values for the enumeration JavaFailureMode
  52         static final String kJavaFailureMainClassNotSpecified = "MainClassNotSpecified";
  53         static final String kJavaFailureMainClassNotFound = "CannotLoadMainClass";
  54         static final String kJavaFailureMainClassHasNoMain = "NoMainMethod";
  55         static final String kJavaFailureMainClassMainNotStatic = "MainNotStatic";
  56         static final String kJavaFailureMainThrewException = "MainThrewException";
  57         static final String kJavaFailureMainInitializerException = "MainInitializerException";
  58 
  59         final boolean verbose; // Normally set by environment variable JAVA_LAUNCHER_VERBOSE.
  60         final Map<String, ?> javaDictionary;
  61 
  62         JavaAppLauncher(final Map<String, ?> javaDictionary, final boolean verbose) {
  63                 this.verbose = verbose;
  64                 this.javaDictionary = javaDictionary;
  65         }
  66 
  67         @Override
  68         public void run() {
  69                 final Method m = loadMainMethod(getMainMethod());
  70                 final String methodName = m.getDeclaringClass().getName() + ".main(String[])";
  71                 try {
  72                         log("Calling " + methodName + " method");
  73                         m.invoke(null, new Object[] { getArguments() });
  74                         log(methodName + " has returned");
  75                 } catch (final IllegalAccessException x) {
  76                         try {
  77                                 nativeInvokeNonPublic(m.getClass(), m, getArguments());
  78                         } catch (final Throwable excpt) {
  79                                 logError(methodName + " threw an exception:");
  80                                 if ((excpt instanceof UnsatisfiedLinkError) && excpt.getMessage().equals("nativeInvokeNonPublic")) {
  81                                         showFailureAlertAndKill(kJavaFailureMainThrewException, "nativeInvokeNonPublic not registered");
  82                                 } else {
  83                                         excpt.printStackTrace();
  84                                         showFailureAlertAndKill(kJavaFailureMainThrewException, excpt.toString());
  85                                 }
  86                         }
  87                 } catch (final InvocationTargetException invokeExcpt) {
  88                         logError(methodName + " threw an exception:");
  89                         invokeExcpt.getTargetException().printStackTrace();
  90                         showFailureAlertAndKill(kJavaFailureMainThrewException, invokeExcpt.getTargetException().toString());
  91                 }
  92         }
  93 
  94         Method loadMainMethod(final String mainClassName) {
  95                 try {
  96                         final Class<?> mainClass = Class.forName(mainClassName, true, sun.misc.Launcher.getLauncher().getClassLoader());
  97                         final Method mainMethod = mainClass.getDeclaredMethod("main", new Class[] { String[].class });
  98                         if ((mainMethod.getModifiers() & Modifier.STATIC) == 0) {
  99                                 logError("The main(String[]) method of class " + mainClassName + " is not static!");
 100                                 showFailureAlertAndKill(kJavaFailureMainClassMainNotStatic, mainClassName);
 101                         }
 102                         return mainMethod;
 103                 } catch (final ExceptionInInitializerError x) {
 104                         logError("The main class \"" + mainClassName + "\" had a static initializer throw an exception.");
 105                         x.getException().printStackTrace();
 106                         showFailureAlertAndKill(kJavaFailureMainInitializerException, x.getException().toString());
 107                 } catch (final ClassNotFoundException x) {
 108                         logError("The main class \"" + mainClassName + "\" could not be found.");
 109                         showFailureAlertAndKill(kJavaFailureMainClassNotFound, mainClassName);
 110                 } catch (final NoSuchMethodException x) {
 111                         logError("The main class \"" + mainClassName + "\" has no static main(String[]) method.");
 112                         showFailureAlertAndKill(kJavaFailureMainClassHasNoMain, mainClassName);
 113                 } catch (final NullPointerException x) {
 114                         logError("No main class specified");
 115                         showFailureAlertAndKill(kJavaFailureMainClassNotSpecified, null);
 116                 }
 117 
 118                 return null;
 119         }
 120 
 121         // get main class name from 'Jar' key, or 'MainClass' key
 122         String getMainMethod() {
 123                 final Object javaJar = javaDictionary.get("Jar");
 124                 if (javaJar != null) {
 125                         if (!(javaJar instanceof String)) {
 126                                 logError("'Jar' key in 'Java' sub-dictionary of Info.plist requires a string value");
 127                                 return null;
 128                         }
 129 
 130                         final String jarPath = (String)javaJar;
 131                         if (jarPath.length() == 0) {
 132                                 log("'Jar' key of sub-dictionary 'Java' of Info.plist key is empty");
 133                         } else {
 134                                 // extract main class from manifest of this jar
 135                                 final String main = getMainFromManifest(jarPath);
 136                                 if (main == null) {
 137                                         logError("jar file '" + jarPath + "' does not have Main-Class: attribute in its manifest");
 138                                         return null;
 139                                 }
 140 
 141                                 log("Main class " + main + " found in jar manifest");
 142                                 return main;
 143                         }
 144                 }
 145 
 146                 final Object javaMain = javaDictionary.get("MainClass");
 147                 if (!(javaMain instanceof String)) {
 148                         logError("'MainClass' key in 'Java' sub-dictionary of Info.plist requires a string value");
 149                         return null;
 150                 }
 151 
 152                 final String main = (String)javaMain;
 153                 if (main.length() == 0) {
 154                         log("'MainClass' key of sub-dictionary 'Java' of Info.plist key is empty");
 155                         return null;
 156                 }
 157 
 158                 log("Main class " + (String)javaMain + " found via 'MainClass' key of sub-dictionary 'Java' of Info.plist key");
 159                 return (String)javaMain;
 160         }
 161 
 162         // get arguments for main(String[]) out of Info.plist and command line
 163         String[] getArguments() {
 164                 // check for 'Arguments' key, which contains the main() args if not defined in Info.plist
 165                 final Object javaArguments = javaDictionary.get("Arguments");
 166                 if (javaArguments == null) {
 167                         // no arguments
 168                         log("No arguments for main(String[]) specified");
 169                         return new String[0];
 170                 }
 171 
 172                 if (javaArguments instanceof List) {
 173                         final List<?> args = (List<?>)javaArguments;
 174                         final int count = args.size();
 175                         log("Arguments to main(String[" + count + "]):");
 176 
 177                         final String[] result = new String[count];
 178                         for (int i = 0; i < count; ++i) {
 179                                 final Object element = args.get(i);
 180                                 if (element instanceof String) {
 181                                         result[i] = (String)element;
 182                                 } else {
 183                                         logError("Found non-string in array");
 184                                 }
 185                                 log("   arg[" + i + "]=" + result[i]);
 186                         }
 187                         return result;
 188                 }
 189 
 190                 logError("'Arguments' key in 'Java' sub-dictionary of Info.plist requires a string value or an array of strings");
 191                 return new String[0];
 192         }
 193 
 194         // returns name of main class, or null
 195         String getMainFromManifest(final String jarpath) {
 196                 JarFile jar = null;
 197                 try {
 198                         jar = new JarFile(jarpath);
 199                         final Manifest man = jar.getManifest();
 200                         final Attributes attr = man.getMainAttributes();
 201                         return attr.getValue("Main-Class");
 202                 } catch (final IOException x) {
 203                         // shrug
 204                 } finally {
 205                         if (jar != null) {
 206                                 try {
 207                                         jar.close();
 208                                 } catch (final IOException x) { }
 209                         }
 210                 }
 211                 return null;
 212         }
 213 
 214         void log(final String s) {
 215                 if (!verbose) return;
 216                 System.out.println("[LaunchRunner] " + s);
 217         }
 218 
 219         static void logError(final String s) {
 220                 System.err.println("[LaunchRunner Error] " + s);
 221         }
 222 
 223         // This kills the app and does not return!
 224         static void showFailureAlertAndKill(final String msg, String arg) {
 225                 if (arg == null) arg = "<<null>>";
 226                 JOptionPane.showMessageDialog(null, getMessage(msg, arg), "", JOptionPane.ERROR_MESSAGE);
 227                 System.exit(-1);
 228         }
 229 
 230         static String getMessage(final String msgKey, final Object ... args) {
 231             final String msg = ResourceBundle.getBundle("appLauncherErrors").getString(msgKey);
 232             return MessageFormat.format(msg, args);
 233         }
 234 }