changeset 1015:c93664c68ae5

launcher from linux, with patch for gethrtime
author bachmann
date Fri, 23 Oct 2009 10:48:33 -0700
parents fc2f92c37235
children 0512bf73ad56
files src/os/haiku/launcher/java.c src/os/haiku/launcher/java.h src/os/haiku/launcher/java_md.c src/os/haiku/launcher/java_md.h
diffstat 4 files changed, 3883 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/os/haiku/launcher/java.c	Fri Oct 23 10:48:33 2009 -0700
@@ -0,0 +1,1842 @@
+/*
+ * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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
+ * published by the Free Software Foundation.
+ *
+ * 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.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+/*
+ * Gamma (Hotspot internal engineering test) launcher based on 1.6.0-b28 JDK,
+ * search "GAMMA" for gamma specific changes.
+ *
+ * GAMMA: gamma launcher is much simpler than regular java launcher in that
+ *        JVM is either statically linked in or it is installed in the
+ *        same directory where the launcher exists, so we don't have to
+ *        worry about choosing the right JVM based on command line flag, jar
+ *        file and/or ergonomics. Intead of removing unused logic from source
+ *        they are commented out with #ifndef GAMMA, hopefully it'll be easier
+ *        to maintain this file in sync with regular JDK launcher.
+ */
+
+/*
+ * Shared source for 'java' command line tool.
+ *
+ * If JAVA_ARGS is defined, then acts as a launcher for applications. For
+ * instance, the JDK command line tools such as javac and javadoc (see
+ * makefiles for more details) are built with this program.  Any arguments
+ * prefixed with '-J' will be passed directly to the 'java' command.
+ */
+
+#ifdef GAMMA
+#  ifdef JAVA_ARGS
+#    error Do NOT define JAVA_ARGS when building gamma launcher
+#  endif
+#  if !defined(LINK_INTO_AOUT) && !defined(LINK_INTO_LIBJVM)
+#    error Either LINK_INTO_AOUT or LINK_INTO_LIBJVM must be defined
+#  endif
+#endif
+
+/*
+ * One job of the launcher is to remove command line options which the
+ * vm does not understand and will not process.  These options include
+ * options which select which style of vm is run (e.g. -client and
+ * -server) as well as options which select the data model to use.
+ * Additionally, for tools which invoke an underlying vm "-J-foo"
+ * options are turned into "-foo" options to the vm.  This option
+ * filtering is handled in a number of places in the launcher, some of
+ * it in machine-dependent code.  In this file, the function
+ * CheckJVMType removes vm style options and TranslateDashJArgs
+ * removes "-J" prefixes.  On unix platforms, the
+ * CreateExecutionEnvironment function from the unix java_md.c file
+ * processes and removes -d<n> options.  However, in case
+ * CreateExecutionEnvironment does not need to exec because
+ * LD_LIBRARY_PATH is set acceptably and the data model does not need
+ * to be changed, ParseArguments will screen out the redundant -d<n>
+ * options and prevent them from being passed to the vm; this is done
+ * by using the machine-dependent call
+ * RemovableMachineDependentOption.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <jni.h>
+#include "java.h"
+
+#ifndef GAMMA
+#include "manifest_info.h"
+#include "version_comp.h"
+#endif
+
+#ifndef FULL_VERSION
+#define FULL_VERSION JDK_MAJOR_VERSION "." JDK_MINOR_VERSION
+#endif
+
+/*
+ * The following environment variable is used to influence the behavior
+ * of the jre exec'd through the SelectVersion routine.  The command line
+ * options which specify the version are not passed to the exec'd version,
+ * because that jre may be an older version which wouldn't recognize them.
+ * This environment variable is known to this (and later) version and serves
+ * to suppress the version selection code.  This is not only for efficiency,
+ * but also for correctness, since any command line options have been
+ * removed which would cause any value found in the manifest to be used.
+ * This would be incorrect because the command line options are defined
+ * to take precedence.
+ *
+ * The value associated with this environment variable is the MainClass
+ * name from within the executable jar file (if any). This is strictly a
+ * performance enhancement to avoid re-reading the jar file manifest.
+ *
+ * A NOTE TO DEVELOPERS: For performance reasons it is important that
+ * the program image remain relatively small until after SelectVersion
+ * CreateExecutionEnvironment have finished their possibly recursive
+ * processing. Watch everything, but resist all temptations to use Java
+ * interfaces.
+ */
+#define ENV_ENTRY "_JAVA_VERSION_SET"
+
+static jboolean printVersion = JNI_FALSE; /* print and exit */
+static jboolean showVersion = JNI_FALSE;  /* print but continue */
+static char *progname;
+jboolean _launcher_debug = JNI_FALSE;
+
+/*
+ * List of VM options to be specified when the VM is created.
+ */
+static JavaVMOption *options;
+static int numOptions, maxOptions;
+
+/*
+ * Prototypes for functions internal to launcher.
+ */
+static void AddOption(char *str, void *info);
+static void SetClassPath(char *s);
+static void SelectVersion(int argc, char **argv, char **main_class);
+static jboolean ParseArguments(int *pargc, char ***pargv, char **pjarfile,
+                               char **pclassname, int *pret);
+static jboolean InitializeJVM(JavaVM **pvm, JNIEnv **penv,
+                              InvocationFunctions *ifn);
+static jstring NewPlatformString(JNIEnv *env, char *s);
+static jobjectArray NewPlatformStringArray(JNIEnv *env, char **strv, int strc);
+static jclass LoadClass(JNIEnv *env, char *name);
+static jstring GetMainClassName(JNIEnv *env, char *jarname);
+static void SetJavaCommandLineProp(char* classname, char* jarfile, int argc, char** argv);
+#ifdef GAMMA
+static void SetJavaLauncherProp(void);
+#endif
+
+#ifdef JAVA_ARGS
+static void TranslateDashJArgs(int *pargc, char ***pargv);
+static jboolean AddApplicationOptions(void);
+#endif
+
+static void PrintJavaVersion(JNIEnv *env);
+static void PrintUsage(void);
+static jint PrintXUsage(void);
+
+static void SetPaths(int argc, char **argv);
+
+/* Maximum supported entries from jvm.cfg. */
+#define INIT_MAX_KNOWN_VMS      10
+/* Values for vmdesc.flag */
+#define VM_UNKNOWN              -1
+#define VM_KNOWN                 0
+#define VM_ALIASED_TO            1
+#define VM_WARN                  2
+#define VM_ERROR                 3
+#define VM_IF_SERVER_CLASS       4
+#define VM_IGNORE                5
+struct vmdesc {
+    char *name;
+    int flag;
+    char *alias;
+    char *server_class;
+};
+static struct vmdesc *knownVMs = NULL;
+static int knownVMsCount = 0;
+static int knownVMsLimit = 0;
+
+static void GrowKnownVMs();
+static int  KnownVMIndex(const char* name);
+static void FreeKnownVMs();
+
+jboolean ServerClassMachine();
+
+/* flag which if set suppresses error messages from the launcher */
+static int noExitErrorMessage = 0;
+
+/*
+ * Entry point.
+ */
+int
+main(int argc, char ** argv)
+{
+    JavaVM *vm = 0;
+    JNIEnv *env = 0;
+    char *jarfile = 0;
+    char *classname = 0;
+    char *s = 0;
+    char *main_class = NULL;
+    jstring mainClassName;
+    jclass mainClass;
+    jmethodID mainID;
+    jobjectArray mainArgs;
+    int ret;
+    InvocationFunctions ifn;
+    jlong start, end;
+    char jrepath[MAXPATHLEN], jvmpath[MAXPATHLEN];
+    char ** original_argv = argv;
+
+    /*
+     * Error message to print or display; by default the message will
+     * only be displayed in a window.
+     */
+    char * message = "Fatal exception occurred.  Program will exit.";
+    jboolean messageDest = JNI_FALSE;
+
+    if (getenv("_JAVA_LAUNCHER_DEBUG") != 0) {
+        _launcher_debug = JNI_TRUE;
+        printf("----_JAVA_LAUNCHER_DEBUG----\n");
+    }
+
+#ifndef GAMMA
+    /*
+     * Make sure the specified version of the JRE is running.
+     *
+     * There are three things to note about the SelectVersion() routine:
+     *  1) If the version running isn't correct, this routine doesn't
+     *     return (either the correct version has been exec'd or an error
+     *     was issued).
+     *  2) Argc and Argv in this scope are *not* altered by this routine.
+     *     It is the responsibility of subsequent code to ignore the
+     *     arguments handled by this routine.
+     *  3) As a side-effect, the variable "main_class" is guaranteed to
+     *     be set (if it should ever be set).  This isn't exactly the
+     *     poster child for structured programming, but it is a small
+     *     price to pay for not processing a jar file operand twice.
+     *     (Note: This side effect has been disabled.  See comment on
+     *     bugid 5030265 below.)
+     */
+    SelectVersion(argc, argv, &main_class);
+#endif /* ifndef GAMMA */
+
+    /* copy original argv */
+    {
+      int i;
+      original_argv = (char**)MemAlloc(sizeof(char*)*(argc+1));
+      for(i = 0; i < argc+1; i++)
+        original_argv[i] = argv[i];
+    }
+
+    CreateExecutionEnvironment(&argc, &argv,
+                               jrepath, sizeof(jrepath),
+                               jvmpath, sizeof(jvmpath),
+                               original_argv);
+    ifn.CreateJavaVM = 0;
+    ifn.GetDefaultJavaVMInitArgs = 0;
+
+    if (_launcher_debug)
+      start = CounterGet();
+    if (!LoadJavaVM(jvmpath, &ifn)) {
+      exit(6);
+    }
+    if (_launcher_debug) {
+      end   = CounterGet();
+      printf("%ld micro seconds to LoadJavaVM\n",
+             (long)(jint)Counter2Micros(end-start));
+    }
+
+#ifdef JAVA_ARGS  /* javac, jar and friends. */
+    progname = "java";
+#else             /* java, oldjava, javaw and friends */
+#ifdef PROGNAME
+    progname = PROGNAME;
+#else
+    progname = *argv;
+    if ((s = strrchr(progname, FILE_SEPARATOR)) != 0) {
+        progname = s + 1;
+    }
+#endif /* PROGNAME */
+#endif /* JAVA_ARGS */
+    ++argv;
+    --argc;
+
+#ifdef JAVA_ARGS
+    /* Preprocess wrapper arguments */
+    TranslateDashJArgs(&argc, &argv);
+    if (!AddApplicationOptions()) {
+        exit(1);
+    }
+#endif
+
+    /* Set default CLASSPATH */
+    if ((s = getenv("CLASSPATH")) == 0) {
+        s = ".";
+    }
+#ifndef JAVA_ARGS
+    SetClassPath(s);
+#endif
+
+    /*
+     *  Parse command line options; if the return value of
+     *  ParseArguments is false, the program should exit.
+     */
+    if (!ParseArguments(&argc, &argv, &jarfile, &classname, &ret)) {
+      exit(ret);
+    }
+
+    /* Override class path if -jar flag was specified */
+    if (jarfile != 0) {
+        SetClassPath(jarfile);
+    }
+
+    /* set the -Dsun.java.command pseudo property */
+    SetJavaCommandLineProp(classname, jarfile, argc, argv);
+
+#ifdef GAMMA
+    /* Set the -Dsun.java.launcher pseudo property */
+    SetJavaLauncherProp();
+#endif
+
+    /*
+     * Done with all command line processing and potential re-execs so
+     * clean up the environment.
+     */
+    (void)UnsetEnv(ENV_ENTRY);
+
+    /* Initialize the virtual machine */
+
+    if (_launcher_debug)
+        start = CounterGet();
+    if (!InitializeJVM(&vm, &env, &ifn)) {
+        ReportErrorMessage("Could not create the Java virtual machine.",
+                           JNI_TRUE);
+        exit(1);
+    }
+
+    if (printVersion || showVersion) {
+        PrintJavaVersion(env);
+        if ((*env)->ExceptionOccurred(env)) {
+            ReportExceptionDescription(env);
+            goto leave;
+        }
+        if (printVersion) {
+            ret = 0;
+            message = NULL;
+            goto leave;
+        }
+        if (showVersion) {
+            fprintf(stderr, "\n");
+        }
+    }
+
+    /* If the user specified neither a class name nor a JAR file */
+    if (jarfile == 0 && classname == 0) {
+        PrintUsage();
+        message = NULL;
+        goto leave;
+    }
+
+#ifndef GAMMA
+    FreeKnownVMs();  /* after last possible PrintUsage() */
+#endif
+
+    if (_launcher_debug) {
+        end   = CounterGet();
+        printf("%ld micro seconds to InitializeJVM\n",
+               (long)(jint)Counter2Micros(end-start));
+    }
+
+    /* At this stage, argc/argv have the applications' arguments */
+    if (_launcher_debug) {
+        int i = 0;
+        printf("Main-Class is '%s'\n", classname ? classname : "");
+        printf("Apps' argc is %d\n", argc);
+        for (; i < argc; i++) {
+            printf("    argv[%2d] = '%s'\n", i, argv[i]);
+        }
+    }
+
+    ret = 1;
+
+    /*
+     * Get the application's main class.
+     *
+     * See bugid 5030265.  The Main-Class name has already been parsed
+     * from the manifest, but not parsed properly for UTF-8 support.
+     * Hence the code here ignores the value previously extracted and
+     * uses the pre-existing code to reextract the value.  This is
+     * possibly an end of release cycle expedient.  However, it has
+     * also been discovered that passing some character sets through
+     * the environment has "strange" behavior on some variants of
+     * Windows.  Hence, maybe the manifest parsing code local to the
+     * launcher should never be enhanced.
+     *
+     * Hence, future work should either:
+     *     1)   Correct the local parsing code and verify that the
+     *          Main-Class attribute gets properly passed through
+     *          all environments,
+     *     2)   Remove the vestages of maintaining main_class through
+     *          the environment (and remove these comments).
+     */
+    if (jarfile != 0) {
+        mainClassName = GetMainClassName(env, jarfile);
+        if ((*env)->ExceptionOccurred(env)) {
+            ReportExceptionDescription(env);
+            goto leave;
+        }
+        if (mainClassName == NULL) {
+          const char * format = "Failed to load Main-Class manifest "
+                                "attribute from\n%s";
+          message = (char*)MemAlloc((strlen(format) + strlen(jarfile)) *
+                                    sizeof(char));
+          sprintf(message, format, jarfile);
+          messageDest = JNI_TRUE;
+          goto leave;
+        }
+        classname = (char *)(*env)->GetStringUTFChars(env, mainClassName, 0);
+        if (classname == NULL) {
+            ReportExceptionDescription(env);
+            goto leave;
+        }
+        mainClass = LoadClass(env, classname);
+        if(mainClass == NULL) { /* exception occurred */
+            ReportExceptionDescription(env);
+            message = "Could not find the main class.  Program will exit.";
+            goto leave;
+        }
+        (*env)->ReleaseStringUTFChars(env, mainClassName, classname);
+    } else {
+      mainClassName = NewPlatformString(env, classname);
+      if (mainClassName == NULL) {
+        const char * format = "Failed to load Main Class: %s";
+        message = (char *)MemAlloc((strlen(format) + strlen(classname)) *
+                                   sizeof(char) );
+        sprintf(message, format, classname);
+        messageDest = JNI_TRUE;
+        goto leave;
+      }
+      classname = (char *)(*env)->GetStringUTFChars(env, mainClassName, 0);
+      if (classname == NULL) {
+        ReportExceptionDescription(env);
+        goto leave;
+      }
+      mainClass = LoadClass(env, classname);
+      if(mainClass == NULL) { /* exception occurred */
+        ReportExceptionDescription(env);
+        message = "Could not find the main class. Program will exit.";
+        goto leave;
+      }
+      (*env)->ReleaseStringUTFChars(env, mainClassName, classname);
+    }
+
+    /* Get the application's main method */
+    mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
+                                       "([Ljava/lang/String;)V");
+    if (mainID == NULL) {
+        if ((*env)->ExceptionOccurred(env)) {
+            ReportExceptionDescription(env);
+        } else {
+          message = "No main method found in specified class.";
+          messageDest = JNI_TRUE;
+        }
+        goto leave;
+    }
+
+    {    /* Make sure the main method is public */
+        jint mods;
+        jmethodID mid;
+        jobject obj = (*env)->ToReflectedMethod(env, mainClass,
+                                                mainID, JNI_TRUE);
+
+        if( obj == NULL) { /* exception occurred */
+            ReportExceptionDescription(env);
+            goto leave;
+        }
+
+        mid =
+          (*env)->GetMethodID(env,
+                              (*env)->GetObjectClass(env, obj),
+                              "getModifiers", "()I");
+        if ((*env)->ExceptionOccurred(env)) {
+            ReportExceptionDescription(env);
+            goto leave;
+        }
+
+        mods = (*env)->CallIntMethod(env, obj, mid);
+        if ((mods & 1) == 0) { /* if (!Modifier.isPublic(mods)) ... */
+            message = "Main method not public.";
+            messageDest = JNI_TRUE;
+            goto leave;
+        }
+    }
+
+    /* Build argument array */
+    mainArgs = NewPlatformStringArray(env, argv, argc);
+    if (mainArgs == NULL) {
+        ReportExceptionDescription(env);
+        goto leave;
+    }
+
+    /* Invoke main method. */
+    (*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);
+
+    /*
+     * The launcher's exit code (in the absence of calls to
+     * System.exit) will be non-zero if main threw an exception.
+     */
+    ret = (*env)->ExceptionOccurred(env) == NULL ? 0 : 1;
+
+    /*
+     * Detach the main thread so that it appears to have ended when
+     * the application's main method exits.  This will invoke the
+     * uncaught exception handler machinery if main threw an
+     * exception.  An uncaught exception handler cannot change the
+     * launcher's return code except by calling System.exit.
+     */
+    if ((*vm)->DetachCurrentThread(vm) != 0) {
+        message = "Could not detach main thread.";
+        messageDest = JNI_TRUE;
+        ret = 1;
+        goto leave;
+    }
+
+    message = NULL;
+
+ leave:
+    /*
+     * Wait for all non-daemon threads to end, then destroy the VM.
+     * This will actually create a trivial new Java waiter thread
+     * named "DestroyJavaVM", but this will be seen as a different
+     * thread from the one that executed main, even though they are
+     * the same C thread.  This allows mainThread.join() and
+     * mainThread.isAlive() to work as expected.
+     */
+    (*vm)->DestroyJavaVM(vm);
+
+    if(message != NULL && !noExitErrorMessage)
+      ReportErrorMessage(message, messageDest);
+    return ret;
+}
+
+
+#ifndef GAMMA
+/*
+ * Checks the command line options to find which JVM type was
+ * specified.  If no command line option was given for the JVM type,
+ * the default type is used.  The environment variable
+ * JDK_ALTERNATE_VM and the command line option -XXaltjvm= are also
+ * checked as ways of specifying which JVM type to invoke.
+ */
+char *
+CheckJvmType(int *pargc, char ***argv, jboolean speculative) {
+    int i, argi;
+    int argc;
+    char **newArgv;
+    int newArgvIdx = 0;
+    int isVMType;
+    int jvmidx = -1;
+    char *jvmtype = getenv("JDK_ALTERNATE_VM");
+
+    argc = *pargc;
+
+    /* To make things simpler we always copy the argv array */
+    newArgv = MemAlloc((argc + 1) * sizeof(char *));
+
+    /* The program name is always present */
+    newArgv[newArgvIdx++] = (*argv)[0];
+
+    for (argi = 1; argi < argc; argi++) {
+        char *arg = (*argv)[argi];
+        isVMType = 0;
+
+#ifdef JAVA_ARGS
+        if (arg[0] != '-') {
+            newArgv[newArgvIdx++] = arg;
+            continue;
+        }
+#else
+        if (strcmp(arg, "-classpath") == 0 ||
+            strcmp(arg, "-cp") == 0) {
+            newArgv[newArgvIdx++] = arg;
+            argi++;
+            if (argi < argc) {
+                newArgv[newArgvIdx++] = (*argv)[argi];
+            }
+            continue;
+        }
+        if (arg[0] != '-') break;
+#endif
+
+        /* Did the user pass an explicit VM type? */
+        i = KnownVMIndex(arg);
+        if (i >= 0) {
+            jvmtype = knownVMs[jvmidx = i].name + 1; /* skip the - */
+            isVMType = 1;
+            *pargc = *pargc - 1;
+        }
+
+        /* Did the user specify an "alternate" VM? */
+        else if (strncmp(arg, "-XXaltjvm=", 10) == 0 || strncmp(arg, "-J-XXaltjvm=", 12) == 0) {
+            isVMType = 1;
+            jvmtype = arg+((arg[1]=='X')? 10 : 12);
+            jvmidx = -1;
+        }
+
+        if (!isVMType) {
+            newArgv[newArgvIdx++] = arg;
+        }
+    }
+
+    /*
+     * Finish copying the arguments if we aborted the above loop.
+     * NOTE that if we aborted via "break" then we did NOT copy the
+     * last argument above, and in addition argi will be less than
+     * argc.
+     */
+    while (argi < argc) {
+        newArgv[newArgvIdx++] = (*argv)[argi];
+        argi++;
+    }
+
+    /* argv is null-terminated */
+    newArgv[newArgvIdx] = 0;
+
+    /* Copy back argv */
+    *argv = newArgv;
+    *pargc = newArgvIdx;
+
+    /* use the default VM type if not specified (no alias processing) */
+    if (jvmtype == NULL) {
+      char* result = knownVMs[0].name+1;
+      /* Use a different VM type if we are on a server class machine? */
+      if ((knownVMs[0].flag == VM_IF_SERVER_CLASS) &&
+          (ServerClassMachine() == JNI_TRUE)) {
+        result = knownVMs[0].server_class+1;
+      }
+      if (_launcher_debug) {
+        printf("Default VM: %s\n", result);
+      }
+      return result;
+    }
+
+    /* if using an alternate VM, no alias processing */
+    if (jvmidx < 0)
+      return jvmtype;
+
+    /* Resolve aliases first */
+    {
+      int loopCount = 0;
+      while (knownVMs[jvmidx].flag == VM_ALIASED_TO) {
+        int nextIdx = KnownVMIndex(knownVMs[jvmidx].alias);
+
+        if (loopCount > knownVMsCount) {
+          if (!speculative) {
+            ReportErrorMessage("Error: Corrupt jvm.cfg file; cycle in alias list.",
+                               JNI_TRUE);
+            exit(1);
+          } else {
+            return "ERROR";
+            /* break; */
+          }
+        }
+
+        if (nextIdx < 0) {
+          if (!speculative) {
+            ReportErrorMessage2("Error: Unable to resolve VM alias %s",
+                                knownVMs[jvmidx].alias, JNI_TRUE);
+            exit(1);
+          } else {
+            return "ERROR";
+          }
+        }
+        jvmidx = nextIdx;
+        jvmtype = knownVMs[jvmidx].name+1;
+        loopCount++;
+      }
+    }
+
+    switch (knownVMs[jvmidx].flag) {
+    case VM_WARN:
+        if (!speculative) {
+            fprintf(stderr, "Warning: %s VM not supported; %s VM will be used\n",
+                    jvmtype, knownVMs[0].name + 1);
+        }
+        /* fall through */
+    case VM_IGNORE:
+        jvmtype = knownVMs[jvmidx=0].name + 1;
+        /* fall through */
+    case VM_KNOWN:
+        break;
+    case VM_ERROR:
+        if (!speculative) {
+            ReportErrorMessage2("Error: %s VM not supported", jvmtype, JNI_TRUE);
+            exit(1);
+        } else {
+            return "ERROR";
+        }
+    }
+
+    return jvmtype;
+}
+#endif /* ifndef GAMMA */
+
+/*
+ * Adds a new VM option with the given given name and value.
+ */
+static void
+AddOption(char *str, void *info)
+{
+    /*
+     * Expand options array if needed to accommodate at least one more
+     * VM option.
+     */
+    if (numOptions >= maxOptions) {
+        if (options == 0) {
+            maxOptions = 4;
+            options = MemAlloc(maxOptions * sizeof(JavaVMOption));
+        } else {
+            JavaVMOption *tmp;
+            maxOptions *= 2;
+            tmp = MemAlloc(maxOptions * sizeof(JavaVMOption));
+            memcpy(tmp, options, numOptions * sizeof(JavaVMOption));
+            free(options);
+            options = tmp;
+        }
+    }
+    options[numOptions].optionString = str;
+    options[numOptions++].extraInfo = info;
+}
+
+static void
+SetClassPath(char *s)
+{
+    char *def = MemAlloc(strlen(s) + 40);
+    sprintf(def, "-Djava.class.path=%s", s);
+    AddOption(def, NULL);
+}
+
+#ifndef GAMMA
+/*
+ * The SelectVersion() routine ensures that an appropriate version of
+ * the JRE is running.  The specification for the appropriate version
+ * is obtained from either the manifest of a jar file (preferred) or
+ * from command line options.
+ */
+static void
+SelectVersion(int argc, char **argv, char **main_class)
+{
+    char    *arg;
+    char    **new_argv;
+    char    **new_argp;
+    char    *operand;
+    char    *version = NULL;
+    char    *jre = NULL;
+    int     jarflag = 0;
+    int     restrict_search = -1;               /* -1 implies not known */
+    manifest_info info;
+    char    env_entry[MAXNAMELEN + 24] = ENV_ENTRY "=";
+    char    *env_in;
+    int     res;
+
+    /*
+     * If the version has already been selected, set *main_class
+     * with the value passed through the environment (if any) and
+     * simply return.
+     */
+    if ((env_in = getenv(ENV_ENTRY)) != NULL) {
+        if (*env_in != '\0')
+            *main_class = strdup(env_in);
+        return;
+    }
+
+    /*
+     * Scan through the arguments for options relevant to multiple JRE
+     * support.  For reference, the command line syntax is defined as:
+     *
+     * SYNOPSIS
+     *      java [options] class [argument...]
+     *
+     *      java [options] -jar file.jar [argument...]
+     *
+     * As the scan is performed, make a copy of the argument list with
+     * the version specification options (new to 1.5) removed, so that
+     * a version less than 1.5 can be exec'd.
+     */
+    new_argv = MemAlloc((argc + 1) * sizeof(char*));
+    new_argv[0] = argv[0];
+    new_argp = &new_argv[1];
+    argc--;
+    argv++;
+    while ((arg = *argv) != 0 && *arg == '-') {
+        if (strncmp(arg, "-version:", 9) == 0) {
+            version = arg + 9;
+        } else if (strcmp(arg, "-jre-restrict-search") == 0) {
+            restrict_search = 1;
+        } else if (strcmp(arg, "-no-jre-restrict-search") == 0) {
+            restrict_search = 0;
+        } else {
+            if (strcmp(arg, "-jar") == 0)
+                jarflag = 1;
+            /* deal with "unfortunate" classpath syntax */
+            if ((strcmp(arg, "-classpath") == 0 || strcmp(arg, "-cp") == 0) &&
+              (argc >= 2)) {
+                *new_argp++ = arg;
+                argc--;
+                argv++;
+                arg = *argv;
+            }
+            *new_argp++ = arg;
+        }
+        argc--;
+        argv++;
+    }
+    if (argc <= 0) {    /* No operand? Possibly legit with -[full]version */
+        operand = NULL;
+    } else {
+        argc--;
+        *new_argp++ = operand = *argv++;
+    }
+    while (argc-- > 0)  /* Copy over [argument...] */
+        *new_argp++ = *argv++;
+    *new_argp = NULL;
+
+    /*
+     * If there is a jar file, read the manifest. If the jarfile can't be
+     * read, the manifest can't be read from the jar file, or the manifest
+     * is corrupt, issue the appropriate error messages and exit.
+     *
+     * Even if there isn't a jar file, construct a manifest_info structure
+     * containing the command line information.  It's a convenient way to carry
+     * this data around.
+     */
+    if (jarflag && operand) {
+        if ((res = parse_manifest(operand, &info)) != 0) {
+            if (res == -1)
+                ReportErrorMessage2("Unable to access jarfile %s",
+                  operand, JNI_TRUE);
+            else
+                ReportErrorMessage2("Invalid or corrupt jarfile %s",
+                  operand, JNI_TRUE);
+            exit(1);
+        }
+    } else {
+        info.manifest_version = NULL;
+        info.main_class = NULL;
+        info.jre_version = NULL;
+        info.jre_restrict_search = 0;
+    }
+
+    /*
+     * The JRE-Version and JRE-Restrict-Search values (if any) from the
+     * manifest are overwritten by any specified on the command line.
+     */
+    if (version != NULL)
+        info.jre_version = version;
+    if (restrict_search != -1)
+        info.jre_restrict_search = restrict_search;
+
+    /*
+     * "Valid" returns (other than unrecoverable errors) follow.  Set
+     * main_class as a side-effect of this routine.
+     */
+    if (info.main_class != NULL)
+        *main_class = strdup(info.main_class);
+
+    /*
+     * If no version selection information is found either on the command
+     * line or in the manifest, simply return.
+     */
+    if (info.jre_version == NULL) {
+        free_manifest();
+        free(new_argv);
+        return;
+    }
+
+    /*
+     * Check for correct syntax of the version specification (JSR 56).
+     */
+    if (!valid_version_string(info.jre_version)) {
+        ReportErrorMessage2("Syntax error in version specification \"%s\"",
+          info.jre_version, JNI_TRUE);
+        exit(1);
+    }
+
+    /*
+     * Find the appropriate JVM on the system. Just to be as forgiving as
+     * possible, if the standard algorithms don't locate an appropriate
+     * jre, check to see if the one running will satisfy the requirements.
+     * This can happen on systems which haven't been set-up for multiple
+     * JRE support.
+     */
+    jre = LocateJRE(&info);
+    if (_launcher_debug)
+        printf("JRE-Version = %s, JRE-Restrict-Search = %s Selected = %s\n",
+          (info.jre_version?info.jre_version:"null"),
+          (info.jre_restrict_search?"true":"false"), (jre?jre:"null"));
+    if (jre == NULL) {
+        if (acceptable_release(FULL_VERSION, info.jre_version)) {
+            free_manifest();
+            free(new_argv);
+            return;
+        } else {
+            ReportErrorMessage2(
+              "Unable to locate JRE meeting specification \"%s\"",
+              info.jre_version, JNI_TRUE);
+            exit(1);
+        }
+    }
+
+    /*
+     * If I'm not the chosen one, exec the chosen one.  Returning from
+     * ExecJRE indicates that I am indeed the chosen one.
+     *
+     * The private environment variable _JAVA_VERSION_SET is used to
+     * prevent the chosen one from re-reading the manifest file and
+     * using the values found within to override the (potential) command
+     * line flags stripped from argv (because the target may not
+     * understand them).  Passing the MainClass value is an optimization
+     * to avoid locating, expanding and parsing the manifest extra
+     * times.
+     */
+    if (info.main_class != NULL)
+        (void)strcat(env_entry, info.main_class);
+    (void)putenv(env_entry);
+    ExecJRE(jre, new_argv);
+    free_manifest();
+    free(new_argv);
+    return;
+}
+#endif /* ifndef GAMMA */
+
+/*
+ * Parses command line arguments.  Returns JNI_FALSE if launcher
+ * should exit without starting vm (e.g. certain version and usage
+ * options); returns JNI_TRUE if vm needs to be started to process
+ * given options.  *pret (the launcher process return value) is set to
+ * 0 for a normal exit.
+ */
+static jboolean
+ParseArguments(int *pargc, char ***pargv, char **pjarfile,
+                       char **pclassname, int *pret)
+{
+    int argc = *pargc;
+    char **argv = *pargv;
+    jboolean jarflag = JNI_FALSE;
+    char *arg;
+
+    *pret = 1;
+    while ((arg = *argv) != 0 && *arg == '-') {
+        argv++; --argc;
+        if (strcmp(arg, "-classpath") == 0 || strcmp(arg, "-cp") == 0) {
+            if (argc < 1) {
+                ReportErrorMessage2("%s requires class path specification",
+                                    arg, JNI_TRUE);
+                PrintUsage();
+                return JNI_FALSE;
+            }
+            SetClassPath(*argv);
+            argv++; --argc;
+        } else if (strcmp(arg, "-jar") == 0) {
+            jarflag = JNI_TRUE;
+        } else if (strcmp(arg, "-help") == 0 ||
+                   strcmp(arg, "-h") == 0 ||
+                   strcmp(arg, "-?") == 0) {
+            PrintUsage();
+            *pret = 0;
+            return JNI_FALSE;
+        } else if (strcmp(arg, "-version") == 0) {
+            printVersion = JNI_TRUE;
+            return JNI_TRUE;
+        } else if (strcmp(arg, "-showversion") == 0) {
+            showVersion = JNI_TRUE;
+        } else if (strcmp(arg, "-X") == 0) {
+            *pret = PrintXUsage();
+            return JNI_FALSE;
+/*
+ * The following case provide backward compatibility with old-style
+ * command line options.
+ */
+        } else if (strcmp(arg, "-fullversion") == 0) {
+            fprintf(stderr, "%s full version \"%s\"\n", progname,
+                    FULL_VERSION);
+            *pret = 0;
+            return JNI_FALSE;
+        } else if (strcmp(arg, "-verbosegc") == 0) {
+            AddOption("-verbose:gc", NULL);
+        } else if (strcmp(arg, "-t") == 0) {
+            AddOption("-Xt", NULL);
+        } else if (strcmp(arg, "-tm") == 0) {
+            AddOption("-Xtm", NULL);
+        } else if (strcmp(arg, "-debug") == 0) {
+            AddOption("-Xdebug", NULL);
+        } else if (strcmp(arg, "-noclassgc") == 0) {
+            AddOption("-Xnoclassgc", NULL);
+        } else if (strcmp(arg, "-Xfuture") == 0) {
+            AddOption("-Xverify:all", NULL);
+        } else if (strcmp(arg, "-verify") == 0) {
+            AddOption("-Xverify:all", NULL);
+        } else if (strcmp(arg, "-verifyremote") == 0) {
+            AddOption("-Xverify:remote", NULL);
+        } else if (strcmp(arg, "-noverify") == 0) {
+            AddOption("-Xverify:none", NULL);
+        } else if (strcmp(arg, "-XXsuppressExitMessage") == 0) {
+            noExitErrorMessage = 1;
+        } else if (strncmp(arg, "-prof", 5) == 0) {
+            char *p = arg + 5;
+            char *tmp = MemAlloc(strlen(arg) + 50);
+            if (*p) {
+                sprintf(tmp, "-Xrunhprof:cpu=old,file=%s", p + 1);
+            } else {
+                sprintf(tmp, "-Xrunhprof:cpu=old,file=java.prof");
+            }
+            AddOption(tmp, NULL);
+        } else if (strncmp(arg, "-ss", 3) == 0 ||
+                   strncmp(arg, "-oss", 4) == 0 ||
+                   strncmp(arg, "-ms", 3) == 0 ||
+                   strncmp(arg, "-mx", 3) == 0) {
+            char *tmp = MemAlloc(strlen(arg) + 6);
+            sprintf(tmp, "-X%s", arg + 1); /* skip '-' */
+            AddOption(tmp, NULL);
+        } else if (strcmp(arg, "-checksource") == 0 ||
+                   strcmp(arg, "-cs") == 0 ||
+                   strcmp(arg, "-noasyncgc") == 0) {
+            /* No longer supported */
+            fprintf(stderr,
+                    "Warning: %s option is no longer supported.\n",
+                    arg);
+        } else if (strncmp(arg, "-version:", 9) == 0 ||
+                   strcmp(arg, "-no-jre-restrict-search") == 0 ||
+                   strcmp(arg, "-jre-restrict-search") == 0) {
+            ; /* Ignore machine independent options already handled */
+        } else if (RemovableMachineDependentOption(arg) ) {
+            ; /* Do not pass option to vm. */
+        }
+        else {
+            AddOption(arg, NULL);
+        }
+    }
+
+    if (--argc >= 0) {
+        if (jarflag) {
+            *pjarfile = *argv++;
+            *pclassname = 0;
+        } else {
+            *pjarfile = 0;
+            *pclassname = *argv++;
+        }
+        *pargc = argc;
+        *pargv = argv;
+    }
+
+    return JNI_TRUE;
+}
+
+/*
+ * Initializes the Java Virtual Machine. Also frees options array when
+ * finished.
+ */
+static jboolean
+InitializeJVM(JavaVM **pvm, JNIEnv **penv, InvocationFunctions *ifn)
+{
+    JavaVMInitArgs args;
+    jint r;
+
+    memset(&args, 0, sizeof(args));
+    args.version  = JNI_VERSION_1_2;
+    args.nOptions = numOptions;
+    args.options  = options;
+    args.ignoreUnrecognized = JNI_FALSE;
+
+    if (_launcher_debug) {
+        int i = 0;
+        printf("JavaVM args:\n    ");
+        printf("version 0x%08lx, ", (long)args.version);
+        printf("ignoreUnrecognized is %s, ",
+               args.ignoreUnrecognized ? "JNI_TRUE" : "JNI_FALSE");
+        printf("nOptions is %ld\n", (long)args.nOptions);
+        for (i = 0; i < numOptions; i++)
+            printf("    option[%2d] = '%s'\n",
+                   i, args.options[i].optionString);
+    }
+
+    r = ifn->CreateJavaVM(pvm, (void **)penv, &args);
+    free(options);
+    return r == JNI_OK;
+}
+
+
+#define NULL_CHECK0(e) if ((e) == 0) return 0
+#define NULL_CHECK(e) if ((e) == 0) return
+
+/*
+ * Returns a pointer to a block of at least 'size' bytes of memory.
+ * Prints error message and exits if the memory could not be allocated.
+ */
+void *
+MemAlloc(size_t size)
+{
+    void *p = malloc(size);
+    if (p == 0) {
+        perror("malloc");
+        exit(1);
+    }
+    return p;
+}
+
+static jstring platformEncoding = NULL;
+static jstring getPlatformEncoding(JNIEnv *env) {
+    if (platformEncoding == NULL) {
+        jstring propname = (*env)->NewStringUTF(env, "sun.jnu.encoding");
+        if (propname) {
+            jclass cls;
+            jmethodID mid;
+            NULL_CHECK0 (cls = FindBootStrapClass(env, "java/lang/System"));
+            NULL_CHECK0 (mid = (*env)->GetStaticMethodID(
+                                   env, cls,
+                                   "getProperty",
+                                   "(Ljava/lang/String;)Ljava/lang/String;"));
+            platformEncoding = (*env)->CallStaticObjectMethod (
+                                    env, cls, mid, propname);
+        }
+    }
+    return platformEncoding;
+}
+
+static jboolean isEncodingSupported(JNIEnv *env, jstring enc) {
+    jclass cls;
+    jmethodID mid;
+    NULL_CHECK0 (cls = FindBootStrapClass(env, "java/nio/charset/Charset"));
+    NULL_CHECK0 (mid = (*env)->GetStaticMethodID(
+                           env, cls,
+                           "isSupported",
+                           "(Ljava/lang/String;)Z"));
+    return (*env)->CallStaticBooleanMethod (env, cls, mid, enc);
+}
+
+/*
+ * Returns a new Java string object for the specified platform string.
+ */
+static jstring
+NewPlatformString(JNIEnv *env, char *s)
+{
+    int len = (int)strlen(s);
+    jclass cls;
+    jmethodID mid;
+    jbyteArray ary;
+    jstring enc;
+
+    if (s == NULL)
+        return 0;
+    enc = getPlatformEncoding(env);
+
+    ary = (*env)->NewByteArray(env, len);
+    if (ary != 0) {
+        jstring str = 0;
+        (*env)->SetByteArrayRegion(env, ary, 0, len, (jbyte *)s);
+        if (!(*env)->ExceptionOccurred(env)) {
+#ifdef GAMMA
+            /* We support running JVM with older JDK, so here we have to deal */
+            /* with the case that sun.jnu.encoding is undefined (enc == NULL) */
+            if (enc != NULL && isEncodingSupported(env, enc) == JNI_TRUE) {
+#else
+            if (isEncodingSupported(env, enc) == JNI_TRUE) {
+#endif
+                NULL_CHECK0(cls = FindBootStrapClass(env, "java/lang/String"));
+                NULL_CHECK0(mid = (*env)->GetMethodID(env, cls, "<init>",
+                                          "([BLjava/lang/String;)V"));
+                str = (*env)->NewObject(env, cls, mid, ary, enc);
+            } else {
+                /*If the encoding specified in sun.jnu.encoding is not
+                  endorsed by "Charset.isSupported" we have to fall back
+                  to use String(byte[]) explicitly here without specifying
+                  the encoding name, in which the StringCoding class will
+                  pickup the iso-8859-1 as the fallback converter for us.
+                */
+                NULL_CHECK0(cls = FindBootStrapClass(env, "java/lang/String"));
+                NULL_CHECK0(mid = (*env)->GetMethodID(env, cls, "<init>",
+                                          "([B)V"));
+                str = (*env)->NewObject(env, cls, mid, ary);
+            }
+            (*env)->DeleteLocalRef(env, ary);
+            return str;
+        }
+    }
+    return 0;
+}
+
+/*
+ * Returns a new array of Java string objects for the specified
+ * array of platform strings.
+ */
+static jobjectArray
+NewPlatformStringArray(JNIEnv *env, char **strv, int strc)
+{
+    jarray cls;
+    jarray ary;
+    int i;
+
+    NULL_CHECK0(cls = FindBootStrapClass(env, "java/lang/String"));
+    NULL_CHECK0(ary = (*env)->NewObjectArray(env, strc, cls, 0));
+    for (i = 0; i < strc; i++) {
+        jstring str = NewPlatformString(env, *strv++);
+        NULL_CHECK0(str);
+        (*env)->SetObjectArrayElement(env, ary, i, str);
+        (*env)->DeleteLocalRef(env, str);
+    }
+    return ary;
+}
+
+/*
+ * Loads a class, convert the '.' to '/'.
+ */
+static jclass
+LoadClass(JNIEnv *env, char *name)
+{
+    char *buf = MemAlloc(strlen(name) + 1);
+    char *s = buf, *t = name, c;
+    jclass cls;
+    jlong start, end;
+
+    if (_launcher_debug)
+        start = CounterGet();
+
+    do {
+        c = *t++;
+        *s++ = (c == '.') ? '/' : c;
+    } while (c != '\0');
+    // use the application class loader for main-class
+    cls = (*env)->FindClass(env, buf);
+    free(buf);
+
+    if (_launcher_debug) {
+        end   = CounterGet();
+        printf("%ld micro seconds to load main class\n",
+               (long)(jint)Counter2Micros(end-start));
+        printf("----_JAVA_LAUNCHER_DEBUG----\n");
+    }
+
+    return cls;
+}
+
+
+/*
+ * Returns the main class name for the specified jar file.
+ */
+static jstring
+GetMainClassName(JNIEnv *env, char *jarname)
+{
+#define MAIN_CLASS "Main-Class"
+    jclass cls;
+    jmethodID mid;
+    jobject jar, man, attr;
+    jstring str, result = 0;
+
+    NULL_CHECK0(cls = FindBootStrapClass(env, "java/util/jar/JarFile"));
+    NULL_CHECK0(mid = (*env)->GetMethodID(env, cls, "<init>",
+                                          "(Ljava/lang/String;)V"));
+    NULL_CHECK0(str = NewPlatformString(env, jarname));
+    NULL_CHECK0(jar = (*env)->NewObject(env, cls, mid, str));
+    NULL_CHECK0(mid = (*env)->GetMethodID(env, cls, "getManifest",
+                                          "()Ljava/util/jar/Manifest;"));
+    man = (*env)->CallObjectMethod(env, jar, mid);
+    if (man != 0) {
+        NULL_CHECK0(mid = (*env)->GetMethodID(env,
+                                    (*env)->GetObjectClass(env, man),
+                                    "getMainAttributes",
+                                    "()Ljava/util/jar/Attributes;"));
+        attr = (*env)->CallObjectMethod(env, man, mid);
+        if (attr != 0) {
+            NULL_CHECK0(mid = (*env)->GetMethodID(env,
+                                    (*env)->GetObjectClass(env, attr),
+                                    "getValue",
+                                    "(Ljava/lang/String;)Ljava/lang/String;"));
+            NULL_CHECK0(str = NewPlatformString(env, MAIN_CLASS));
+            result = (*env)->CallObjectMethod(env, attr, mid, str);
+        }
+    }
+    return result;
+}
+
+#ifdef JAVA_ARGS
+static char *java_args[] = JAVA_ARGS;
+static char *app_classpath[] = APP_CLASSPATH;
+
+/*
+ * For tools convert 'javac -J-ms32m' to 'java -ms32m ...'
+ */
+static void
+TranslateDashJArgs(int *pargc, char ***pargv)
+{
+    const int NUM_ARGS = (sizeof(java_args) / sizeof(char *));
+    int argc = *pargc;
+    char **argv = *pargv;
+    int nargc = argc + NUM_ARGS;
+    char **nargv = MemAlloc((nargc + 1) * sizeof(char *));
+    int i;
+
+    *pargc = nargc;
+    *pargv = nargv;
+
+    /* Copy the VM arguments (i.e. prefixed with -J) */
+    for (i = 0; i < NUM_ARGS; i++) {
+        char *arg = java_args[i];
+        if (arg[0] == '-' && arg[1] == 'J') {
+            *nargv++ = arg + 2;
+        }
+    }
+
+    for (i = 0; i < argc; i++) {
+        char *arg = argv[i];
+        if (arg[0] == '-' && arg[1] == 'J') {
+            if (arg[2] == '\0') {
+                ReportErrorMessage("Error: the -J option should not be "
+                                   "followed by a space.", JNI_TRUE);
+                exit(1);
+            }
+            *nargv++ = arg + 2;
+        }
+    }
+
+    /* Copy the rest of the arguments */
+    for (i = 0; i < NUM_ARGS; i++) {
+        char *arg = java_args[i];
+        if (arg[0] != '-' || arg[1] != 'J') {
+            *nargv++ = arg;
+        }
+    }
+    for (i = 0; i < argc; i++) {
+        char *arg = argv[i];
+        if (arg[0] != '-' || arg[1] != 'J') {
+            *nargv++ = arg;
+        }
+    }
+    *nargv = 0;
+}
+
+/*
+ * For our tools, we try to add 3 VM options:
+ *      -Denv.class.path=<envcp>
+ *      -Dapplication.home=<apphome>
+ *      -Djava.class.path=<appcp>
+ * <envcp>   is the user's setting of CLASSPATH -- for instance the user
+ *           tells javac where to find binary classes through this environment
+ *           variable.  Notice that users will be able to compile against our
+ *           tools classes (sun.tools.javac.Main) only if they explicitly add
+ *           tools.jar to CLASSPATH.
+ * <apphome> is the directory where the application is installed.
+ * <appcp>   is the classpath to where our apps' classfiles are.
+ */
+static jboolean
+AddApplicationOptions()
+{
+    const int NUM_APP_CLASSPATH = (sizeof(app_classpath) / sizeof(char *));
+    char *s, *envcp, *appcp, *apphome;
+    char home[MAXPATHLEN]; /* application home */
+    char separator[] = { PATH_SEPARATOR, '\0' };
+    int size, i;
+    int strlenHome;
+
+    s = getenv("CLASSPATH");
+    if (s) {
+        /* 40 for -Denv.class.path= */
+        envcp = (char *)MemAlloc(strlen(s) + 40);
+        sprintf(envcp, "-Denv.class.path=%s", s);
+        AddOption(envcp, NULL);
+    }
+
+    if (!GetApplicationHome(home, sizeof(home))) {
+        ReportErrorMessage("Can't determine application home", JNI_TRUE);
+        return JNI_FALSE;
+    }
+
+    /* 40 for '-Dapplication.home=' */
+    apphome = (char *)MemAlloc(strlen(home) + 40);
+    sprintf(apphome, "-Dapplication.home=%s", home);
+    AddOption(apphome, NULL);
+
+    /* How big is the application's classpath? */
+    size = 40;                                 /* 40: "-Djava.class.path=" */
+    strlenHome = (int)strlen(home);
+    for (i = 0; i < NUM_APP_CLASSPATH; i++) {
+        size += strlenHome + (int)strlen(app_classpath[i]) + 1; /* 1: separator */
+    }
+    appcp = (char *)MemAlloc(size + 1);
+    strcpy(appcp, "-Djava.class.path=");
+    for (i = 0; i < NUM_APP_CLASSPATH; i++) {
+        strcat(appcp, home);                    /* c:\program files\myapp */
+        strcat(appcp, app_classpath[i]);        /* \lib\myapp.jar         */
+        strcat(appcp, separator);               /* ;                      */
+    }
+    appcp[strlen(appcp)-1] = '\0';  /* remove trailing path separator */
+    AddOption(appcp, NULL);
+    return JNI_TRUE;
+}
+#endif
+
+/*
+ * inject the -Dsun.java.command pseudo property into the args structure
+ * this pseudo property is used in the HotSpot VM to expose the
+ * Java class name and arguments to the main method to the VM. The
+ * HotSpot VM uses this pseudo property to store the Java class name
+ * (or jar file name) and the arguments to the class's main method
+ * to the instrumentation memory region. The sun.java.command pseudo
+ * property is not exported by HotSpot to the Java layer.
+ */
+void
+SetJavaCommandLineProp(char *classname, char *jarfile,
+                       int argc, char **argv)
+{
+
+    int i = 0;
+    size_t len = 0;
+    char* javaCommand = NULL;
+    char* dashDstr = "-Dsun.java.command=";
+
+    if (classname == NULL && jarfile == NULL) {
+        /* unexpected, one of these should be set. just return without
+         * setting the property
+         */
+        return;
+    }
+
+    /* if the class name is not set, then use the jarfile name */
+    if (classname == NULL) {
+        classname = jarfile;
+    }
+
+    /* determine the amount of memory to allocate assuming
+     * the individual components will be space separated
+     */
+    len = strlen(classname);
+    for (i = 0; i < argc; i++) {
+        len += strlen(argv[i]) + 1;
+    }
+
+    /* allocate the memory */
+    javaCommand = (char*) MemAlloc(len + strlen(dashDstr) + 1);
+
+    /* build the -D string */
+    *javaCommand = '\0';
+    strcat(javaCommand, dashDstr);
+    strcat(javaCommand, classname);
+
+    for (i = 0; i < argc; i++) {
+        /* the components of the string are space separated. In
+         * the case of embedded white space, the relationship of
+         * the white space separated components to their true
+         * positional arguments will be ambiguous. This issue may
+         * be addressed in a future release.
+         */
+        strcat(javaCommand, " ");
+        strcat(javaCommand, argv[i]);
+    }
+
+    AddOption(javaCommand, NULL);
+}
+
+/*
+ * JVM wants to know launcher type, so tell it.
+ */
+#ifdef GAMMA
+void SetJavaLauncherProp() {
+  AddOption("-Dsun.java.launcher=" LAUNCHER_TYPE, NULL);
+}
+#endif
+
+/*
+ * Prints the version information from the java.version and other properties.
+ */
+static void
+PrintJavaVersion(JNIEnv *env)
+{
+    jclass ver;
+    jmethodID print;
+
+    NULL_CHECK(ver = FindBootStrapClass(env, "sun/misc/Version"));
+    NULL_CHECK(print = (*env)->GetStaticMethodID(env, ver, "print", "()V"));
+
+    (*env)->CallStaticVoidMethod(env, ver, print);
+}
+
+/*
+ * Prints default usage message.
+ */
+static void
+PrintUsage(void)
+{
+    int i;
+
+    fprintf(stdout,
+        "Usage: %s [-options] class [args...]\n"
+        "           (to execute a class)\n"
+        "   or  %s [-options] -jar jarfile [args...]\n"
+        "           (to execute a jar file)\n"
+        "\n"
+        "where options include:\n",
+        progname,
+        progname);
+
+#ifndef GAMMA
+    PrintMachineDependentOptions();
+
+    if ((knownVMs[0].flag == VM_KNOWN) ||
+        (knownVMs[0].flag == VM_IF_SERVER_CLASS)) {
+      fprintf(stdout, "    %s\t  to select the \"%s\" VM\n",
+              knownVMs[0].name, knownVMs[0].name+1);
+    }
+    for (i=1; i<knownVMsCount; i++) {
+        if (knownVMs[i].flag == VM_KNOWN)
+            fprintf(stdout, "    %s\t  to select the \"%s\" VM\n",
+                    knownVMs[i].name, knownVMs[i].name+1);
+    }
+    for (i=1; i<knownVMsCount; i++) {
+        if (knownVMs[i].flag == VM_ALIASED_TO)
+            fprintf(stdout, "    %s\t  is a synonym for "
+                    "the \"%s\" VM  [deprecated]\n",
+                    knownVMs[i].name, knownVMs[i].alias+1);
+    }
+
+    /* The first known VM is the default */
+    {
+      const char* defaultVM   = knownVMs[0].name+1;
+      const char* punctuation = ".";
+      const char* reason      = "";
+      if ((knownVMs[0].flag == VM_IF_SERVER_CLASS) &&
+          (ServerClassMachine() == JNI_TRUE)) {
+        defaultVM = knownVMs[0].server_class+1;
+        punctuation = ", ";
+        reason = "because you are running on a server-class machine.\n";
+      }
+      fprintf(stdout, "                  The default VM is %s%s\n",
+              defaultVM, punctuation);
+      fprintf(stdout, "                  %s\n",
+              reason);
+    }
+#endif /* ifndef GAMMA */
+
+    fprintf(stdout,
+"    -cp <class search path of directories and zip/jar files>\n"
+"    -classpath <class search path of directories and zip/jar files>\n"
+"                  A %c separated list of directories, JAR archives,\n"
+"                  and ZIP archives to search for class files.\n"
+"    -D<name>=<value>\n"
+"                  set a system property\n"
+"    -verbose[:class|gc|jni]\n"
+"                  enable verbose output\n"
+"    -version      print product version and exit\n"
+"    -version:<value>\n"
+"                  require the specified version to run\n"
+"    -showversion  print product version and continue\n"
+"    -jre-restrict-search | -jre-no-restrict-search\n"
+"                  include/exclude user private JREs in the version search\n"
+"    -? -help      print this help message\n"
+"    -X            print help on non-standard options\n"
+"    -ea[:<packagename>...|:<classname>]\n"
+"    -enableassertions[:<packagename>...|:<classname>]\n"
+"                  enable assertions\n"
+"    -da[:<packagename>...|:<classname>]\n"
+"    -disableassertions[:<packagename>...|:<classname>]\n"
+"                  disable assertions\n"
+"    -esa | -enablesystemassertions\n"
+"                  enable system assertions\n"
+"    -dsa | -disablesystemassertions\n"
+"                  disable system assertions\n"
+"    -agentlib:<libname>[=<options>]\n"
+"                  load native agent library <libname>, e.g. -agentlib:hprof\n"
+"                    see also, -agentlib:jdwp=help and -agentlib:hprof=help\n"
+"    -agentpath:<pathname>[=<options>]\n"
+"                  load native agent library by full pathname\n"
+"    -javaagent:<jarpath>[=<options>]\n"
+"                  load Java programming language agent, see java.lang.instrument\n"
+
+            ,PATH_SEPARATOR);
+}
+
+/*
+ * Print usage message for -X options.
+ */
+static jint
+PrintXUsage(void)
+{
+    char path[MAXPATHLEN];
+    char buf[128];
+    size_t n;
+    FILE *fp;
+
+    GetXUsagePath(path, sizeof(path));
+    fp = fopen(path, "r");
+    if (fp == 0) {
+        fprintf(stderr, "Can't open %s\n", path);
+        return 1;
+    }
+    while ((n = fread(buf, 1, sizeof(buf), fp)) != 0) {
+        fwrite(buf, 1, n, stdout);
+    }
+    fclose(fp);
+    return 0;
+}
+
+#ifndef GAMMA
+
+/*
+ * Read the jvm.cfg file and fill the knownJVMs[] array.
+ *
+ * The functionality of the jvm.cfg file is subject to change without
+ * notice and the mechanism will be removed in the future.
+ *
+ * The lexical structure of the jvm.cfg file is as follows:
+ *
+ *     jvmcfg         :=  { vmLine }
+ *     vmLine         :=  knownLine
+ *                    |   aliasLine
+ *                    |   warnLine
+ *                    |   ignoreLine
+ *                    |   errorLine
+ *                    |   predicateLine
+ *                    |   commentLine
+ *     knownLine      :=  flag  "KNOWN"                  EOL
+ *     warnLine       :=  flag  "WARN"                   EOL
+ *     ignoreLine     :=  flag  "IGNORE"                 EOL
+ *     errorLine      :=  flag  "ERROR"                  EOL
+ *     aliasLine      :=  flag  "ALIASED_TO"       flag  EOL
+ *     predicateLine  :=  flag  "IF_SERVER_CLASS"  flag  EOL
+ *     commentLine    :=  "#" text                       EOL
+ *     flag           :=  "-" identifier
+ *
+ * The semantics are that when someone specifies a flag on the command line:
+ * - if the flag appears on a knownLine, then the identifier is used as
+ *   the name of the directory holding the JVM library (the name of the JVM).
+ * - if the flag appears as the first flag on an aliasLine, the identifier
+ *   of the second flag is used as the name of the JVM.
+ * - if the flag appears on a warnLine, the identifier is used as the
+ *   name of the JVM, but a warning is generated.
+ * - if the flag appears on an ignoreLine, the identifier is recognized as the
+ *   name of a JVM, but the identifier is ignored and the default vm used
+ * - if the flag appears on an errorLine, an error is generated.
+ * - if the flag appears as the first flag on a predicateLine, and
+ *   the machine on which you are running passes the predicate indicated,
+ *   then the identifier of the second flag is used as the name of the JVM,
+ *   otherwise the identifier of the first flag is used as the name of the JVM.
+ * If no flag is given on the command line, the first vmLine of the jvm.cfg
+ * file determines the name of the JVM.
+ * PredicateLines are only interpreted on first vmLine of a jvm.cfg file,
+ * since they only make sense if someone hasn't specified the name of the
+ * JVM on the command line.
+ *
+ * The intent of the jvm.cfg file is to allow several JVM libraries to
+ * be installed in different subdirectories of a single JRE installation,
+ * for space-savings and convenience in testing.
+ * The intent is explicitly not to provide a full aliasing or predicate
+ * mechanism.
+ */
+jint
+ReadKnownVMs(const char *jrepath, char * arch, jboolean speculative)
+{
+    FILE *jvmCfg;
+    char jvmCfgName[MAXPATHLEN+20];
+    char line[MAXPATHLEN+20];
+    int cnt = 0;
+    int lineno = 0;
+    jlong start, end;
+    int vmType;
+    char *tmpPtr;
+    char *altVMName;
+    char *serverClassVMName;
+    static char *whiteSpace = " \t";
+    if (_launcher_debug) {
+        start = CounterGet();
+    }
+
+    strcpy(jvmCfgName, jrepath);
+    strcat(jvmCfgName, FILESEP "lib" FILESEP);
+    strcat(jvmCfgName, arch);
+    strcat(jvmCfgName, FILESEP "jvm.cfg");
+
+    jvmCfg = fopen(jvmCfgName, "r");
+    if (jvmCfg == NULL) {
+      if (!speculative) {
+        ReportErrorMessage2("Error: could not open `%s'", jvmCfgName,
+                            JNI_TRUE);
+        exit(1);
+      } else {
+        return -1;
+      }
+    }
+    while (fgets(line, sizeof(line), jvmCfg) != NULL) {
+        vmType = VM_UNKNOWN;
+        lineno++;
+        if (line[0] == '#')
+            continue;
+        if (line[0] != '-') {
+            fprintf(stderr, "Warning: no leading - on line %d of `%s'\n",
+                    lineno, jvmCfgName);
+        }
+        if (cnt >= knownVMsLimit) {
+            GrowKnownVMs(cnt);
+        }
+        line[strlen(line)-1] = '\0'; /* remove trailing newline */
+        tmpPtr = line + strcspn(line, whiteSpace);
+        if (*tmpPtr == 0) {
+            fprintf(stderr, "Warning: missing VM type on line %d of `%s'\n",
+                    lineno, jvmCfgName);
+        } else {
+            /* Null-terminate this string for strdup below */
+            *tmpPtr++ = 0;
+            tmpPtr += strspn(tmpPtr, whiteSpace);
+            if (*tmpPtr == 0) {
+                fprintf(stderr, "Warning: missing VM type on line %d of `%s'\n",
+                        lineno, jvmCfgName);
+            } else {
+                if (!strncmp(tmpPtr, "KNOWN", strlen("KNOWN"))) {
+                    vmType = VM_KNOWN;
+                } else if (!strncmp(tmpPtr, "ALIASED_TO", strlen("ALIASED_TO"))) {
+                    tmpPtr += strcspn(tmpPtr, whiteSpace);
+                    if (*tmpPtr != 0) {
+                        tmpPtr += strspn(tmpPtr, whiteSpace);
+                    }
+                    if (*tmpPtr == 0) {
+                        fprintf(stderr, "Warning: missing VM alias on line %d of `%s'\n",
+                                lineno, jvmCfgName);
+                    } else {
+                        /* Null terminate altVMName */
+                        altVMName = tmpPtr;
+                        tmpPtr += strcspn(tmpPtr, whiteSpace);
+                        *tmpPtr = 0;
+                        vmType = VM_ALIASED_TO;
+                    }
+                } else if (!strncmp(tmpPtr, "WARN", strlen("WARN"))) {
+                    vmType = VM_WARN;
+                } else if (!strncmp(tmpPtr, "IGNORE", strlen("IGNORE"))) {
+                    vmType = VM_IGNORE;
+                } else if (!strncmp(tmpPtr, "ERROR", strlen("ERROR"))) {
+                    vmType = VM_ERROR;
+                } else if (!strncmp(tmpPtr,
+                                    "IF_SERVER_CLASS",
+                                    strlen("IF_SERVER_CLASS"))) {
+                    tmpPtr += strcspn(tmpPtr, whiteSpace);
+                    if (*tmpPtr != 0) {
+                        tmpPtr += strspn(tmpPtr, whiteSpace);
+                    }
+                    if (*tmpPtr == 0) {
+                        fprintf(stderr, "Warning: missing server class VM on line %d of `%s'\n",
+                                lineno, jvmCfgName);
+                    } else {
+                        /* Null terminate server class VM name */
+                        serverClassVMName = tmpPtr;
+                        tmpPtr += strcspn(tmpPtr, whiteSpace);
+                        *tmpPtr = 0;
+                        vmType = VM_IF_SERVER_CLASS;
+                    }
+                } else {
+                    fprintf(stderr, "Warning: unknown VM type on line %d of `%s'\n",
+                            lineno, &jvmCfgName[0]);
+                    vmType = VM_KNOWN;
+                }
+            }
+        }
+
+        if (_launcher_debug)
+            printf("jvm.cfg[%d] = ->%s<-\n", cnt, line);
+        if (vmType != VM_UNKNOWN) {
+            knownVMs[cnt].name = strdup(line);
+            knownVMs[cnt].flag = vmType;
+            switch (vmType) {
+            default:
+                break;
+            case VM_ALIASED_TO:
+                knownVMs[cnt].alias = strdup(altVMName);
+                if (_launcher_debug) {
+                    printf("    name: %s  vmType: %s  alias: %s\n",
+                           knownVMs[cnt].name, "VM_ALIASED_TO", knownVMs[cnt].alias);
+                }
+                break;
+            case VM_IF_SERVER_CLASS:
+                knownVMs[cnt].server_class = strdup(serverClassVMName);
+                if (_launcher_debug) {
+                    printf("    name: %s  vmType: %s  server_class: %s\n",
+                           knownVMs[cnt].name, "VM_IF_SERVER_CLASS", knownVMs[cnt].server_class);
+                }
+                break;
+            }
+            cnt++;
+        }
+    }
+    fclose(jvmCfg);
+    knownVMsCount = cnt;
+
+    if (_launcher_debug) {
+        end   = CounterGet();
+        printf("%ld micro seconds to parse jvm.cfg\n",
+               (long)(jint)Counter2Micros(end-start));
+    }
+
+    return cnt;
+}
+
+
+static void
+GrowKnownVMs(int minimum)
+{
+    struct vmdesc* newKnownVMs;
+    int newMax;
+
+    newMax = (knownVMsLimit == 0 ? INIT_MAX_KNOWN_VMS : (2 * knownVMsLimit));
+    if (newMax <= minimum) {
+        newMax = minimum;
+    }
+    newKnownVMs = (struct vmdesc*) MemAlloc(newMax * sizeof(struct vmdesc));
+    if (knownVMs != NULL) {
+        memcpy(newKnownVMs, knownVMs, knownVMsLimit * sizeof(struct vmdesc));
+    }
+    free(knownVMs);
+    knownVMs = newKnownVMs;
+    knownVMsLimit = newMax;
+}
+
+
+/* Returns index of VM or -1 if not found */
+static int
+KnownVMIndex(const char* name)
+{
+    int i;
+    if (strncmp(name, "-J", 2) == 0) name += 2;
+    for (i = 0; i < knownVMsCount; i++) {
+        if (!strcmp(name, knownVMs[i].name)) {
+            return i;
+        }
+    }
+    return -1;
+}
+
+static void
+FreeKnownVMs()
+{
+    int i;
+    for (i = 0; i < knownVMsCount; i++) {
+        free(knownVMs[i].name);
+        knownVMs[i].name = NULL;
+    }
+    free(knownVMs);
+}
+
+#endif /* ifndef GAMMA */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/os/haiku/launcher/java.h	Fri Oct 23 10:48:33 2009 -0700
@@ -0,0 +1,114 @@
+/*
+ * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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
+ * published by the Free Software Foundation.
+ *
+ * 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.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+/*
+ * Gamma (Hotspot internal engineering test) launcher based on 1.6.0-b28 JDK,
+ * search "GAMMA" for gamma specific changes.
+ */
+
+#ifndef _JAVA_H_
+#define _JAVA_H_
+
+/*
+ * Get system specific defines.
+ */
+#include "jni.h"
+#include "java_md.h"
+
+/*
+ * Pointers to the needed JNI invocation API, initialized by LoadJavaVM.
+ */
+typedef jint (JNICALL *CreateJavaVM_t)(JavaVM **pvm, void **env, void *args);
+typedef jint (JNICALL *GetDefaultJavaVMInitArgs_t)(void *args);
+
+typedef struct {
+    CreateJavaVM_t CreateJavaVM;
+    GetDefaultJavaVMInitArgs_t GetDefaultJavaVMInitArgs;
+} InvocationFunctions;
+
+/*
+ * Prototypes for launcher functions in the system specific java_md.c.
+ */
+
+jboolean
+LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn);
+
+void
+GetXUsagePath(char *buf, jint bufsize);
+
+jboolean
+GetApplicationHome(char *buf, jint bufsize);
+
+const char *
+GetArch();
+
+void CreateExecutionEnvironment(int *_argc,
+                                       char ***_argv,
+                                       char jrepath[],
+                                       jint so_jrepath,
+                                       char jvmpath[],
+                                       jint so_jvmpath,
+                                       char **original_argv);
+
+/*
+ * Report an error message to stderr or a window as appropriate.  The
+ * flag always is set to JNI_TRUE if message is to be reported to both
+ * strerr and windows and set to JNI_FALSE if the message should only
+ * be sent to a window.
+ */
+void ReportErrorMessage(char * message, jboolean always);
+void ReportErrorMessage2(char * format, char * string, jboolean always);
+
+/*
+ * Report an exception which terminates the vm to stderr or a window
+ * as appropriate.
+ */
+void ReportExceptionDescription(JNIEnv * env);
+
+jboolean RemovableMachineDependentOption(char * option);
+void PrintMachineDependentOptions();
+
+/*
+ * Functions defined in java.c and used in java_md.c.
+ */
+jint ReadKnownVMs(const char *jrepath, char * arch, jboolean speculative);
+char *CheckJvmType(int *argc, char ***argv, jboolean speculative);
+void* MemAlloc(size_t size);
+
+/*
+ * Make launcher spit debug output.
+ */
+extern jboolean _launcher_debug;
+/*
+ * This allows for finding classes from the VM's bootstrap class loader
+ * directly, FindClass uses the application class loader internally, this will
+ * cause unnecessary searching of the classpath for the required classes.
+ */
+typedef jclass (JNICALL FindClassFromBootLoader_t(JNIEnv *env,
+                                                const char *name,
+                                                jboolean throwError));
+
+jclass FindBootStrapClass(JNIEnv *env, const char *classname);
+
+#endif /* _JAVA_H_ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/os/haiku/launcher/java_md.c	Fri Oct 23 10:48:33 2009 -0700
@@ -0,0 +1,1848 @@
+/*
+ * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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
+ * published by the Free Software Foundation.
+ *
+ * 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.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+/*
+ * Gamma (Hotspot internal engineering test) launcher based on 1.6.0-b28 JDK,
+ * search "GAMMA" for gamma specific changes.
+ */
+
+#include "java.h"
+#include <dirent.h>
+#include <dlfcn.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <sys/types.h>
+
+#ifndef GAMMA
+#include "manifest_info.h"
+#include "version_comp.h"
+#endif
+
+#define JVM_DLL "libjvm.so"
+#define JAVA_DLL "libjava.so"
+
+#ifndef GAMMA   /* launcher.make defines ARCH */
+
+/*
+ * If a processor / os combination has the ability to run binaries of
+ * two data models and cohabitation of jre/jdk bits with both data
+ * models is supported, then DUAL_MODE is defined.  When DUAL_MODE is
+ * defined, the architecture names for the narrow and wide version of
+ * the architecture are defined in BIG_ARCH and SMALL_ARCH.  Currently
+ * only Solaris on sparc/sparcv9 and i586/amd64 is DUAL_MODE; linux
+ * i586/amd64 could be defined as DUAL_MODE but that is not the
+ * current policy.
+ */
+
+#ifdef _LP64
+
+#  ifdef ia64
+#    define ARCH "ia64"
+#  elif defined(amd64)
+#    define ARCH "amd64"
+#  elif defined(__sparc)
+#    define ARCH "sparcv9"
+#  else
+#    define ARCH "unknown" /* unknown 64-bit architecture */
+#  endif
+
+#else /* 32-bit data model */
+
+#  ifdef i586
+#    define ARCH "i386"
+#  elif defined(__sparc)
+#    define ARCH "sparc"
+#  endif
+
+#endif /* _LP64 */
+
+#ifdef __sun
+#  define DUAL_MODE
+#  ifdef __sparc
+#    define BIG_ARCH "sparcv9"
+#    define SMALL_ARCH "sparc"
+#  else
+#    define BIG_ARCH "amd64"
+#    define SMALL_ARCH "i386"
+#  endif
+#  include <sys/systeminfo.h>
+#  include <sys/elf.h>
+#  include <stdio.h>
+#else
+#  ifndef ARCH
+#    include <sys/systeminfo.h>
+#  endif
+#endif
+
+#endif /* ifndef GAMMA */
+
+/* pointer to environment */
+extern char **environ;
+
+#ifndef GAMMA
+
+/*
+ *      A collection of useful strings. One should think of these as #define
+ *      entries, but actual strings can be more efficient (with many compilers).
+ */
+#ifdef __linux__
+static const char *system_dir   = "/usr/java";
+static const char *user_dir     = "/java";
+#else /* Solaris */
+static const char *system_dir   = "/usr/jdk";
+static const char *user_dir     = "/jdk";
+#endif
+
+#endif  /* ifndef GAMMA */
+
+/*
+ * Flowchart of launcher execs and options processing on unix
+ *
+ * The selection of the proper vm shared library to open depends on
+ * several classes of command line options, including vm "flavor"
+ * options (-client, -server) and the data model options, -d32  and
+ * -d64, as well as a version specification which may have come from
+ * the command line or from the manifest of an executable jar file.
+ * The vm selection options are not passed to the running
+ * virtual machine; they must be screened out by the launcher.
+ *
+ * The version specification (if any) is processed first by the
+ * platform independent routine SelectVersion.  This may result in
+ * the exec of the specified launcher version.
+ *
+ * Typically, the launcher execs at least once to ensure a suitable
+ * LD_LIBRARY_PATH is in effect for the process.  The first exec
+ * screens out all the data model options; leaving the choice of data
+ * model implicit in the binary selected to run.  However, in case no
+ * exec is done, the data model options are screened out before the vm
+ * is invoked.
+ *
+ *  incoming argv ------------------------------
+ *  |                                          |
+ * \|/                                         |
+ * CheckJVMType                                |
+ * (removes -client, -server, etc.)            |
+ *                                            \|/
+ *                                            CreateExecutionEnvironment
+ *                                            (removes -d32 and -d64,
+ *                                             determines desired data model,
+ *                                             sets up LD_LIBRARY_PATH,
+ *                                             and exec's)
+ *                                             |
+ *  --------------------------------------------
+ *  |
+ * \|/
+ * exec child 1 incoming argv -----------------
+ *  |                                          |
+ * \|/                                         |
+ * CheckJVMType                                |
+ * (removes -client, -server, etc.)            |
+ *  |                                         \|/
+ *  |                                          CreateExecutionEnvironment
+ *  |                                          (verifies desired data model
+ *  |                                           is running and acceptable
+ *  |                                           LD_LIBRARY_PATH;
+ *  |                                           no-op in child)
+ *  |
+ * \|/
+ * TranslateDashJArgs...
+ * (Prepare to pass args to vm)
+ *  |
+ *  |
+ *  |
+ * \|/
+ * ParseArguments
+ * (ignores -d32 and -d64,
+ *  processes version options,
+ *  creates argument list for vm,
+ *  etc.)
+ *
+ */
+
+static char *SetExecname(char **argv);
+static char * GetExecname();
+static jboolean GetJVMPath(const char *jrepath, const char *jvmtype,
+                           char *jvmpath, jint jvmpathsize, char * arch);
+static jboolean GetJREPath(char *path, jint pathsize, char * arch, jboolean speculative);
+
+const char *
+GetArch()
+{
+    static char *arch = NULL;
+    static char buf[12];
+    if (arch) {
+        return arch;
+    }
+
+#ifdef ARCH
+    strcpy(buf, ARCH);
+#else
+    sysinfo(SI_ARCHITECTURE, buf, sizeof(buf));
+#endif
+    arch = buf;
+    return arch;
+}
+
+void
+CreateExecutionEnvironment(int *_argcp,
+                           char ***_argvp,
+                           char jrepath[],
+                           jint so_jrepath,
+                           char jvmpath[],
+                           jint so_jvmpath,
+                           char **original_argv) {
+  /*
+   * First, determine if we are running the desired data model.  If we
+   * are running the desired data model, all the error messages
+   * associated with calling GetJREPath, ReadKnownVMs, etc. should be
+   * output.  However, if we are not running the desired data model,
+   * some of the errors should be suppressed since it is more
+   * informative to issue an error message based on whether or not the
+   * os/processor combination has dual mode capabilities.
+   */
+
+    char *execname = NULL;
+    int original_argc = *_argcp;
+    jboolean jvmpathExists;
+
+    /* Compute the name of the executable */
+    execname = SetExecname(*_argvp);
+
+#ifndef GAMMA
+    /* Set the LD_LIBRARY_PATH environment variable, check data model
+       flags, and exec process, if needed */
+    {
+      char *arch        = (char *)GetArch(); /* like sparc or sparcv9 */
+      char * jvmtype    = NULL;
+      int argc          = *_argcp;
+      char **argv       = original_argv;
+
+      char *runpath     = NULL; /* existing effective LD_LIBRARY_PATH
+                                   setting */
+
+      int running       =       /* What data model is being ILP32 =>
+                                   32 bit vm; LP64 => 64 bit vm */
+#ifdef _LP64
+        64;
+#else
+      32;
+#endif
+
+      int wanted        = running;      /* What data mode is being
+                                           asked for? Current model is
+                                           fine unless another model
+                                           is asked for */
+
+      char* new_runpath = NULL; /* desired new LD_LIBRARY_PATH string */
+      char* newpath     = NULL; /* path on new LD_LIBRARY_PATH */
+      char* lastslash   = NULL;
+
+      char** newenvp    = NULL; /* current environment */
+
+      char** newargv    = NULL;
+      int    newargc    = 0;
+#ifdef __sun
+      char*  dmpath     = NULL;  /* data model specific LD_LIBRARY_PATH,
+                                    Solaris only */
+#endif
+
+      /*
+       * Starting in 1.5, all unix platforms accept the -d32 and -d64
+       * options.  On platforms where only one data-model is supported
+       * (e.g. ia-64 Linux), using the flag for the other data model is
+       * an error and will terminate the program.
+       */
+
+      { /* open new scope to declare local variables */
+        int i;
+
+        newargv = (char **)MemAlloc((argc+1) * sizeof(*newargv));
+        newargv[newargc++] = argv[0];
+
+        /* scan for data model arguments and remove from argument list;
+           last occurrence determines desired data model */
+        for (i=1; i < argc; i++) {
+
+          if (strcmp(argv[i], "-J-d64") == 0 || strcmp(argv[i], "-d64") == 0) {
+            wanted = 64;
+            continue;
+          }
+          if (strcmp(argv[i], "-J-d32") == 0 || strcmp(argv[i], "-d32") == 0) {
+            wanted = 32;
+            continue;
+          }
+          newargv[newargc++] = argv[i];
+
+#ifdef JAVA_ARGS
+          if (argv[i][0] != '-')
+            continue;
+#else
+          if (strcmp(argv[i], "-classpath") == 0 || strcmp(argv[i], "-cp") == 0) {
+            i++;
+            if (i >= argc) break;
+            newargv[newargc++] = argv[i];
+            continue;
+          }
+          if (argv[i][0] != '-') { i++; break; }
+#endif
+        }
+
+        /* copy rest of args [i .. argc) */
+        while (i < argc) {
+          newargv[newargc++] = argv[i++];
+        }
+        newargv[newargc] = NULL;
+
+        /*
+         * newargv has all proper arguments here
+         */
+
+        argc = newargc;
+        argv = newargv;
+      }
+
+      /* If the data model is not changing, it is an error if the
+         jvmpath does not exist */
+      if (wanted == running) {
+        /* Find out where the JRE is that we will be using. */
+        if (!GetJREPath(jrepath, so_jrepath, arch, JNI_FALSE) ) {
+          fprintf(stderr, "Error: could not find Java 2 Runtime Environment.\n");
+          exit(2);
+        }
+
+        /* Find the specified JVM type */
+        if (ReadKnownVMs(jrepath, arch, JNI_FALSE) < 1) {
+          fprintf(stderr, "Error: no known VMs. (check for corrupt jvm.cfg file)\n");
+          exit(1);
+        }
+
+        jvmpath[0] = '\0';
+        jvmtype = CheckJvmType(_argcp, _argvp, JNI_FALSE);
+
+        if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, arch )) {
+          fprintf(stderr, "Error: no `%s' JVM at `%s'.\n", jvmtype, jvmpath);
+          exit(4);
+        }
+      } else {  /* do the same speculatively or exit */
+#ifdef DUAL_MODE
+        if (running != wanted) {
+          /* Find out where the JRE is that we will be using. */
+          if (!GetJREPath(jrepath, so_jrepath, ((wanted==64)?BIG_ARCH:SMALL_ARCH), JNI_TRUE)) {
+            goto EndDataModelSpeculate;
+          }
+
+          /*
+           * Read in jvm.cfg for target data model and process vm
+           * selection options.
+           */
+          if (ReadKnownVMs(jrepath, ((wanted==64)?BIG_ARCH:SMALL_ARCH), JNI_TRUE) < 1) {
+            goto EndDataModelSpeculate;
+          }
+          jvmpath[0] = '\0';
+          jvmtype = CheckJvmType(_argcp, _argvp, JNI_TRUE);
+          /* exec child can do error checking on the existence of the path */
+          jvmpathExists = GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath,
+                                     ((wanted==64)?BIG_ARCH:SMALL_ARCH));
+
+        }
+      EndDataModelSpeculate: /* give up and let other code report error message */
+        ;
+#else
+        fprintf(stderr, "Running a %d-bit JVM is not supported on this platform.\n", wanted);
+        exit(1);
+#endif
+      }
+
+      /*
+       * We will set the LD_LIBRARY_PATH as follows:
+       *
+       *     o          $JVMPATH (directory portion only)
+       *     o          $JRE/lib/$ARCH
+       *     o          $JRE/../lib/$ARCH
+       *
+       * followed by the user's previous effective LD_LIBRARY_PATH, if
+       * any.
+       */
+
+#ifdef __sun
+      /*
+       * Starting in Solaris 7, ld.so.1 supports three LD_LIBRARY_PATH
+       * variables:
+       *
+       * 1. LD_LIBRARY_PATH -- used for 32 and 64 bit searches if
+       * data-model specific variables are not set.
+       *
+       * 2. LD_LIBRARY_PATH_64 -- overrides and replaces LD_LIBRARY_PATH
+       * for 64-bit binaries.
+       *
+       * 3. LD_LIBRARY_PATH_32 -- overrides and replaces LD_LIBRARY_PATH
+       * for 32-bit binaries.
+       *
+       * The vm uses LD_LIBRARY_PATH to set the java.library.path system
+       * property.  To shield the vm from the complication of multiple
+       * LD_LIBRARY_PATH variables, if the appropriate data model
+       * specific variable is set, we will act as if LD_LIBRARY_PATH had
+       * the value of the data model specific variant and the data model
+       * specific variant will be unset.  Note that the variable for the
+       * *wanted* data model must be used (if it is set), not simply the
+       * current running data model.
+       */
+
+      switch(wanted) {
+      case 0:
+        if(running == 32) {
+          dmpath = getenv("LD_LIBRARY_PATH_32");
+          wanted = 32;
+        }
+        else {
+          dmpath = getenv("LD_LIBRARY_PATH_64");
+          wanted = 64;
+        }
+        break;
+
+      case 32:
+        dmpath = getenv("LD_LIBRARY_PATH_32");
+        break;
+
+      case 64:
+        dmpath = getenv("LD_LIBRARY_PATH_64");
+        break;
+
+      default:
+        fprintf(stderr, "Improper value at line %d.", __LINE__);
+        exit(1); /* unknown value in wanted */
+        break;
+      }
+
+      /*
+       * If dmpath is NULL, the relevant data model specific variable is
+       * not set and normal LD_LIBRARY_PATH should be used.
+       */
+      if( dmpath == NULL) {
+        runpath = getenv("LD_LIBRARY_PATH");
+      }
+      else {
+        runpath = dmpath;
+      }
+#else
+      /*
+       * If not on Solaris, assume only a single LD_LIBRARY_PATH
+       * variable.
+       */
+      runpath = getenv("LD_LIBRARY_PATH");
+#endif /* __sun */
+
+#ifdef __linux
+      /*
+       * On linux, if a binary is running as sgid or suid, glibc sets
+       * LD_LIBRARY_PATH to the empty string for security purposes.  (In
+       * contrast, on Solaris the LD_LIBRARY_PATH variable for a
+       * privileged binary does not lose its settings; but the dynamic
+       * linker does apply more scrutiny to the path.) The launcher uses
+       * the value of LD_LIBRARY_PATH to prevent an exec loop.
+       * Therefore, if we are running sgid or suid, this function's
+       * setting of LD_LIBRARY_PATH will be ineffective and we should
+       * return from the function now.  Getting the right libraries to
+       * be found must be handled through other mechanisms.
+       */
+      if((getgid() != getegid()) || (getuid() != geteuid()) ) {
+        return;
+      }
+#endif
+
+      /* runpath contains current effective LD_LIBRARY_PATH setting */
+
+      jvmpath = strdup(jvmpath);
+      new_runpath = MemAlloc( ((runpath!=NULL)?strlen(runpath):0) +
+                              2*strlen(jrepath) + 2*strlen(arch) +
+                              strlen(jvmpath) + 52);
+      newpath = new_runpath + strlen("LD_LIBRARY_PATH=");
+
+
+      /*
+       * Create desired LD_LIBRARY_PATH value for target data model.
+       */
+      {
+        /* remove the name of the .so from the JVM path */
+        lastslash = strrchr(jvmpath, '/');
+        if (lastslash)
+          *lastslash = '\0';
+
+
+        /* jvmpath, ((running != wanted)?((wanted==64)?"/"BIG_ARCH:"/.."):""), */
+
+        sprintf(new_runpath, "LD_LIBRARY_PATH="
+                "%s:"
+                "%s/lib/%s:"
+                "%s/../lib/%s",
+                jvmpath,
+#ifdef DUAL_MODE
+                jrepath, ((wanted==64)?BIG_ARCH:SMALL_ARCH),
+                jrepath, ((wanted==64)?BIG_ARCH:SMALL_ARCH)
+#else
+                jrepath, arch,
+                jrepath, arch
+#endif
+                );
+
+
+        /*
+         * Check to make sure that the prefix of the current path is the
+         * desired environment variable setting.
+         */
+        if (runpath != NULL &&
+            strncmp(newpath, runpath, strlen(newpath))==0 &&
+            (runpath[strlen(newpath)] == 0 || runpath[strlen(newpath)] == ':') &&
+            (running == wanted) /* data model does not have to be changed */
+#ifdef __sun
+            && (dmpath == NULL)    /* data model specific variables not set  */
+#endif
+            ) {
+
+          return;
+
+        }
+      }
+
+      /*
+       * Place the desired environment setting onto the prefix of
+       * LD_LIBRARY_PATH.  Note that this prevents any possible infinite
+       * loop of execv() because we test for the prefix, above.
+       */
+      if (runpath != 0) {
+        strcat(new_runpath, ":");
+        strcat(new_runpath, runpath);
+      }
+
+      if( putenv(new_runpath) != 0) {
+        exit(1); /* problem allocating memory; LD_LIBRARY_PATH not set
+                    properly */
+      }
+
+      /*
+       * Unix systems document that they look at LD_LIBRARY_PATH only
+       * once at startup, so we have to re-exec the current executable
+       * to get the changed environment variable to have an effect.
+       */
+
+#ifdef __sun
+      /*
+       * If dmpath is not NULL, remove the data model specific string
+       * in the environment for the exec'ed child.
+       */
+
+      if( dmpath != NULL)
+        (void)UnsetEnv((wanted==32)?"LD_LIBRARY_PATH_32":"LD_LIBRARY_PATH_64");
+#endif
+
+      newenvp = environ;
+
+      {
+        char *newexec = execname;
+#ifdef DUAL_MODE
+        /*
+         * If the data model is being changed, the path to the
+         * executable must be updated accordingly; the executable name
+         * and directory the executable resides in are separate.  In the
+         * case of 32 => 64, the new bits are assumed to reside in, e.g.
+         * "olddir/BIGARCH/execname"; in the case of 64 => 32,
+         * the bits are assumed to be in "olddir/../execname".  For example,
+         *
+         * olddir/sparcv9/execname
+         * olddir/amd64/execname
+         *
+         * for Solaris SPARC and Linux amd64, respectively.
+         */
+
+        if (running != wanted) {
+          char *oldexec = strcpy(MemAlloc(strlen(execname) + 1), execname);
+          char *olddir = oldexec;
+          char *oldbase = strrchr(oldexec, '/');
+
+
+          newexec = MemAlloc(strlen(execname) + 20);
+          *oldbase++ = 0;
+          sprintf(newexec, "%s/%s/%s", olddir,
+                  ((wanted==64) ? BIG_ARCH : ".."), oldbase);
+          argv[0] = newexec;
+        }
+#endif
+
+        execve(newexec, argv, newenvp);
+        perror("execve()");
+
+        fprintf(stderr, "Error trying to exec %s.\n", newexec);
+        fprintf(stderr, "Check if file exists and permissions are set correctly.\n");
+
+#ifdef DUAL_MODE
+        if (running != wanted) {
+          fprintf(stderr, "Failed to start a %d-bit JVM process from a %d-bit JVM.\n",
+                  wanted, running);
+#  ifdef __sun
+
+#    ifdef __sparc
+          fprintf(stderr, "Verify all necessary J2SE components have been installed.\n" );
+          fprintf(stderr,
+                  "(Solaris SPARC 64-bit components must be installed after 32-bit components.)\n" );
+#    else
+          fprintf(stderr, "Either 64-bit processes are not supported by this platform\n");
+          fprintf(stderr, "or the 64-bit components have not been installed.\n");
+#    endif
+        }
+#  endif
+#endif
+
+      }
+
+      exit(1);
+    }
+
+#else  /* ifndef GAMMA */
+
+  /* gamma launcher is simpler in that it doesn't handle VM flavors, data  */
+  /* model, LD_LIBRARY_PATH, etc. Assuming everything is set-up correctly  */
+  /* all we need to do here is to return correct path names. See also      */
+  /* GetJVMPath() and GetApplicationHome().                                */
+
+  { char *arch = (char *)GetArch(); /* like sparc or sparcv9 */
+    char *p;
+
+    if (!GetJREPath(jrepath, so_jrepath, arch, JNI_FALSE) ) {
+      fprintf(stderr, "Error: could not find Java 2 Runtime Environment.\n");
+      exit(2);
+    }
+
+    if (!GetJVMPath(jrepath, NULL, jvmpath, so_jvmpath, arch )) {
+      fprintf(stderr, "Error: no JVM at `%s'.\n", jvmpath);
+      exit(4);
+    }
+  }
+
+#endif  /* ifndef GAMMA */
+}
+
+
+/*
+ * On Solaris VM choosing is done by the launcher (java.c).
+ */
+static jboolean
+GetJVMPath(const char *jrepath, const char *jvmtype,
+           char *jvmpath, jint jvmpathsize, char * arch)
+{
+    struct stat s;
+
+#ifndef GAMMA
+    if (strchr(jvmtype, '/')) {
+        sprintf(jvmpath, "%s/" JVM_DLL, jvmtype);
+    } else {
+        sprintf(jvmpath, "%s/lib/%s/%s/" JVM_DLL, jrepath, arch, jvmtype);
+    }
+#else
+    /* For gamma launcher, JVM is either built-in or in the same directory. */
+    /* Either way we return "<exe_path>/libjvm.so" where <exe_path> is the  */
+    /* directory where gamma launcher is located.                           */
+
+    char *p;
+
+    snprintf(jvmpath, jvmpathsize, "%s", GetExecname());
+    p = strrchr(jvmpath, '/');
+    if (p) {
+       /* replace executable name with libjvm.so */
+       snprintf(p + 1, jvmpathsize - (p + 1 - jvmpath), "%s", JVM_DLL);
+    } else {
+       /* this case shouldn't happen */
+       snprintf(jvmpath, jvmpathsize, "%s", JVM_DLL);
+    }
+#endif
+
+    if (_launcher_debug)
+      printf("Does `%s' exist ... ", jvmpath);
+
+    if (stat(jvmpath, &s) == 0) {
+        if (_launcher_debug)
+          printf("yes.\n");
+        return JNI_TRUE;
+    } else {
+        if (_launcher_debug)
+          printf("no.\n");
+        return JNI_FALSE;
+    }
+}
+
+/*
+ * Find path to JRE based on .exe's location or registry settings.
+ */
+static jboolean
+GetJREPath(char *path, jint pathsize, char * arch, jboolean speculative)
+{
+    char libjava[MAXPATHLEN];
+
+    if (GetApplicationHome(path, pathsize)) {
+        /* Is JRE co-located with the application? */
+        sprintf(libjava, "%s/lib/%s/" JAVA_DLL, path, arch);
+        if (access(libjava, F_OK) == 0) {
+            goto found;
+        }
+
+        /* Does the app ship a private JRE in <apphome>/jre directory? */
+        sprintf(libjava, "%s/jre/lib/%s/" JAVA_DLL, path, arch);
+        if (access(libjava, F_OK) == 0) {
+            strcat(path, "/jre");
+            goto found;
+        }
+    }
+
+    if (!speculative)
+      fprintf(stderr, "Error: could not find " JAVA_DLL "\n");
+    return JNI_FALSE;
+
+ found:
+    if (_launcher_debug)
+      printf("JRE path is %s\n", path);
+    return JNI_TRUE;
+}
+
+jboolean
+LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)
+{
+#ifdef GAMMA
+    /* JVM is directly linked with gamma launcher; no dlopen() */
+    ifn->CreateJavaVM = JNI_CreateJavaVM;
+    ifn->GetDefaultJavaVMInitArgs = JNI_GetDefaultJavaVMInitArgs;
+    return JNI_TRUE;
+#else
+    Dl_info dlinfo;
+    void *libjvm;
+
+    if (_launcher_debug) {
+        printf("JVM path is %s\n", jvmpath);
+    }
+
+    libjvm = dlopen(jvmpath, RTLD_NOW + RTLD_GLOBAL);
+    if (libjvm == NULL) {
+#if defined(__sparc) && !defined(_LP64) /* i.e. 32-bit sparc */
+      FILE * fp;
+      Elf32_Ehdr elf_head;
+      int count;
+      int location;
+
+      fp = fopen(jvmpath, "r");
+      if(fp == NULL)
+        goto error;
+
+      /* read in elf header */
+      count = fread((void*)(&elf_head), sizeof(Elf32_Ehdr), 1, fp);
+      fclose(fp);
+      if(count < 1)
+        goto error;
+
+      /*
+       * Check for running a server vm (compiled with -xarch=v8plus)
+       * on a stock v8 processor.  In this case, the machine type in
+       * the elf header would not be included the architecture list
+       * provided by the isalist command, which is turn is gotten from
+       * sysinfo.  This case cannot occur on 64-bit hardware and thus
+       * does not have to be checked for in binaries with an LP64 data
+       * model.
+       */
+      if(elf_head.e_machine == EM_SPARC32PLUS) {
+        char buf[257];  /* recommended buffer size from sysinfo man
+                           page */
+        long length;
+        char* location;
+
+        length = sysinfo(SI_ISALIST, buf, 257);
+        if(length > 0) {
+          location = strstr(buf, "sparcv8plus ");
+          if(location == NULL) {
+            fprintf(stderr, "SPARC V8 processor detected; Server compiler requires V9 or better.\n");
+            fprintf(stderr, "Use Client compiler on V8 processors.\n");
+            fprintf(stderr, "Could not create the Java virtual machine.\n");
+            return JNI_FALSE;
+          }
+        }
+      }
+#endif
+      fprintf(stderr, "dl failure on line %d", __LINE__);
+      goto error;
+    }
+
+    ifn->CreateJavaVM = (CreateJavaVM_t)
+      dlsym(libjvm, "JNI_CreateJavaVM");
+    if (ifn->CreateJavaVM == NULL)
+        goto error;
+
+    ifn->GetDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs_t)
+        dlsym(libjvm, "JNI_GetDefaultJavaVMInitArgs");
+    if (ifn->GetDefaultJavaVMInitArgs == NULL)
+      goto error;
+
+    return JNI_TRUE;
+
+error:
+    fprintf(stderr, "Error: failed %s, because %s\n", jvmpath, dlerror());
+    return JNI_FALSE;
+#endif /* GAMMA */
+}
+
+/*
+ * Get the path to the file that has the usage message for -X options.
+ */
+void
+GetXUsagePath(char *buf, jint bufsize)
+{
+    static const char Xusage_txt[] = "/Xusage.txt";
+    Dl_info dlinfo;
+
+    /* we use RTLD_NOW because of problems with ld.so.1 and green threads */
+    dladdr(dlsym(dlopen(JVM_DLL, RTLD_NOW), "JNI_CreateJavaVM"), &dlinfo);
+    strncpy(buf, (char *)dlinfo.dli_fname, bufsize - sizeof(Xusage_txt));
+
+    buf[bufsize-1] = '\0';
+    strcpy(strrchr(buf, '/'), Xusage_txt);
+}
+
+/*
+ * If app is "/foo/bin/javac", or "/foo/bin/sparcv9/javac" then put
+ * "/foo" into buf.
+ */
+jboolean
+GetApplicationHome(char *buf, jint bufsize)
+{
+#ifdef __linux__
+    char *execname = GetExecname();
+    if (execname) {
+        strncpy(buf, execname, bufsize-1);
+        buf[bufsize-1] = '\0';
+    } else {
+        return JNI_FALSE;
+    }
+#else
+    Dl_info dlinfo;
+
+    dladdr((void *)GetApplicationHome, &dlinfo);
+    if (realpath(dlinfo.dli_fname, buf) == NULL) {
+        fprintf(stderr, "Error: realpath(`%s') failed.\n", dlinfo.dli_fname);
+        return JNI_FALSE;
+    }
+#endif
+
+#ifdef GAMMA
+    {
+      /* gamma launcher uses JAVA_HOME environment variable to find JDK/JRE */
+      char* java_home_var = getenv("JAVA_HOME");
+      if (java_home_var == NULL) {
+        printf("JAVA_HOME must point to a valid JDK/JRE to run gamma\n");
+        return JNI_FALSE;
+      }
+      snprintf(buf, bufsize, "%s", java_home_var);
+    }
+#else
+    if (strrchr(buf, '/') == 0) {
+        buf[0] = '\0';
+        return JNI_FALSE;
+    }
+    *(strrchr(buf, '/')) = '\0';        /* executable file      */
+    if (strlen(buf) < 4 || strrchr(buf, '/') == 0) {
+        buf[0] = '\0';
+        return JNI_FALSE;
+    }
+    if (strcmp("/bin", buf + strlen(buf) - 4) != 0)
+        *(strrchr(buf, '/')) = '\0';    /* sparcv9 or amd64     */
+    if (strlen(buf) < 4 || strcmp("/bin", buf + strlen(buf) - 4) != 0) {
+        buf[0] = '\0';
+        return JNI_FALSE;
+    }
+    *(strrchr(buf, '/')) = '\0';        /* bin                  */
+#endif /* GAMMA */
+
+    return JNI_TRUE;
+}
+
+
+/*
+ * Return true if the named program exists
+ */
+static int
+ProgramExists(char *name)
+{
+    struct stat sb;
+    if (stat(name, &sb) != 0) return 0;
+    if (S_ISDIR(sb.st_mode)) return 0;
+    return (sb.st_mode & S_IEXEC) != 0;
+}
+
+
+/*
+ * Find a command in a directory, returning the path.
+ */
+static char *
+Resolve(char *indir, char *cmd)
+{
+    char name[PATH_MAX + 2], *real;
+
+    if ((strlen(indir) + strlen(cmd) + 1)  > PATH_MAX) return 0;
+    sprintf(name, "%s%c%s", indir, FILE_SEPARATOR, cmd);
+    if (!ProgramExists(name)) return 0;
+    real = MemAlloc(PATH_MAX + 2);
+    if (!realpath(name, real))
+        strcpy(real, name);
+    return real;
+}
+
+
+/*
+ * Find a path for the executable
+ */
+static char *
+FindExecName(char *program)
+{
+    char cwdbuf[PATH_MAX+2];
+    char *path;
+    char *tmp_path;
+    char *f;
+    char *result = NULL;
+
+    /* absolute path? */
+    if (*program == FILE_SEPARATOR ||
+        (FILE_SEPARATOR=='\\' && strrchr(program, ':')))
+        return Resolve("", program+1);
+
+    /* relative path? */
+    if (strrchr(program, FILE_SEPARATOR) != 0) {
+        char buf[PATH_MAX+2];
+        return Resolve(getcwd(cwdbuf, sizeof(cwdbuf)), program);
+    }
+
+    /* from search path? */
+    path = getenv("PATH");
+    if (!path || !*path) path = ".";
+    tmp_path = MemAlloc(strlen(path) + 2);
+    strcpy(tmp_path, path);
+
+    for (f=tmp_path; *f && result==0; ) {
+        char *s = f;
+        while (*f && (*f != PATH_SEPARATOR)) ++f;
+        if (*f) *f++ = 0;
+        if (*s == FILE_SEPARATOR)
+            result = Resolve(s, program);
+        else {
+            /* relative path element */
+            char dir[2*PATH_MAX];
+            sprintf(dir, "%s%c%s", getcwd(cwdbuf, sizeof(cwdbuf)),
+                    FILE_SEPARATOR, s);
+            result = Resolve(dir, program);
+        }
+        if (result != 0) break;
+    }
+
+    free(tmp_path);
+    return result;
+}
+
+
+/* Store the name of the executable once computed */
+static char *execname = NULL;
+
+/*
+ * Compute the name of the executable
+ *
+ * In order to re-exec securely we need the absolute path of the
+ * executable. On Solaris getexecname(3c) may not return an absolute
+ * path so we use dladdr to get the filename of the executable and
+ * then use realpath to derive an absolute path. From Solaris 9
+ * onwards the filename returned in DL_info structure from dladdr is
+ * an absolute pathname so technically realpath isn't required.
+ * On Linux we read the executable name from /proc/self/exe.
+ * As a fallback, and for platforms other than Solaris and Linux,
+ * we use FindExecName to compute the executable name.
+ */
+static char *
+SetExecname(char **argv)
+{
+    char* exec_path = NULL;
+
+    if (execname != NULL)       /* Already determined */
+        return (execname);
+
+#if defined(__sun)
+    {
+        Dl_info dlinfo;
+        if (dladdr((void*)&SetExecname, &dlinfo)) {
+            char *resolved = (char*)MemAlloc(PATH_MAX+1);
+            if (resolved != NULL) {
+                exec_path = realpath(dlinfo.dli_fname, resolved);
+                if (exec_path == NULL) {
+                    free(resolved);
+                }
+            }
+        }
+    }
+#elif defined(__linux__)
+    {
+        const char* self = "/proc/self/exe";
+        char buf[PATH_MAX+1];
+        int len = readlink(self, buf, PATH_MAX);
+        if (len >= 0) {
+            buf[len] = '\0';            /* readlink doesn't nul terminate */
+            exec_path = strdup(buf);
+        }
+    }
+#else /* !__sun && !__linux */
+    {
+        /* Not implemented */
+    }
+#endif
+
+    if (exec_path == NULL) {
+        exec_path = FindExecName(argv[0]);
+    }
+    execname = exec_path;
+    return exec_path;
+}
+
+/*
+ * Return the name of the executable.  Used in java_md.c to find the JRE area.
+ */
+static char *
+GetExecname() {
+  return execname;
+}
+
+void ReportErrorMessage(char * message, jboolean always) {
+  if (always) {
+    fprintf(stderr, "%s\n", message);
+  }
+}
+
+void ReportErrorMessage2(char * format, char * string, jboolean always) {
+  if (always) {
+    fprintf(stderr, format, string);
+    fprintf(stderr, "\n");
+  }
+}
+
+void  ReportExceptionDescription(JNIEnv * env) {
+  (*env)->ExceptionDescribe(env);
+}
+
+/*
+ * Return JNI_TRUE for an option string that has no effect but should
+ * _not_ be passed on to the vm; return JNI_FALSE otherwise.  On
+ * Solaris SPARC, this screening needs to be done if:
+ * 1) LD_LIBRARY_PATH does _not_ need to be reset and
+ * 2) -d32 or -d64 is passed to a binary with a matching data model
+ *    (the exec in SetLibraryPath removes -d<n> options and points the
+ *    exec to the proper binary).  When this exec is not done, these options
+ *    would end up getting passed onto the vm.
+ */
+jboolean RemovableMachineDependentOption(char * option) {
+  /*
+   * Unconditionally remove both -d32 and -d64 options since only
+   * the last such options has an effect; e.g.
+   * java -d32 -d64 -d32 -version
+   * is equivalent to
+   * java -d32 -version
+   */
+
+  if( (strcmp(option, "-d32")  == 0 ) ||
+      (strcmp(option, "-d64")  == 0 ))
+    return JNI_TRUE;
+  else
+    return JNI_FALSE;
+}
+
+void PrintMachineDependentOptions() {
+      fprintf(stdout,
+        "    -d32          use a 32-bit data model if available\n"
+        "\n"
+        "    -d64          use a 64-bit data model if available\n");
+      return;
+}
+
+#ifndef GAMMA  /* gamma launcher does not have ergonomics */
+
+/*
+ * The following methods (down to ServerClassMachine()) answer
+ * the question about whether a machine is a "server-class"
+ * machine.  A server-class machine is loosely defined as one
+ * with 2 or more processors and 2 gigabytes or more physical
+ * memory.  The definition of a processor is a physical package,
+ * not a hyperthreaded chip masquerading as a multi-processor.
+ * The definition of memory is also somewhat fuzzy, since x86
+ * machines seem not to report all the memory in their DIMMs, we
+ * think because of memory mapping of graphics cards, etc.
+ *
+ * This code is somewhat more confused with #ifdef's than we'd
+ * like because this file is used by both Solaris and Linux
+ * platforms, and so needs to be parameterized for SPARC and
+ * i586 hardware.  The other Linux platforms (amd64 and ia64)
+ * don't even ask this question, because they only come with
+ * server JVMs.  */
+
+# define KB (1024UL)
+# define MB (1024UL * KB)
+# define GB (1024UL * MB)
+
+/* Compute physical memory by asking the OS */
+uint64_t
+physical_memory(void) {
+  const uint64_t pages     = (uint64_t) sysconf(_SC_PHYS_PAGES);
+  const uint64_t page_size = (uint64_t) sysconf(_SC_PAGESIZE);
+  const uint64_t result    = pages * page_size;
+# define UINT64_FORMAT "%" PRIu64
+
+  if (_launcher_debug) {
+    printf("pages: " UINT64_FORMAT
+           "  page_size: " UINT64_FORMAT
+           "  physical memory: " UINT64_FORMAT " (%.3fGB)\n",
+           pages, page_size, result, result / (double) GB);
+  }
+  return result;
+}
+
+#if defined(__sun) && defined(__sparc)
+
+/* Methods for solaris-sparc: these are easy. */
+
+/* Ask the OS how many processors there are. */
+unsigned long
+physical_processors(void) {
+  const unsigned long sys_processors = sysconf(_SC_NPROCESSORS_CONF);
+
+  if (_launcher_debug) {
+    printf("sysconf(_SC_NPROCESSORS_CONF): %lu\n", sys_processors);
+  }
+  return sys_processors;
+}
+
+/* The solaris-sparc version of the "server-class" predicate. */
+jboolean
+solaris_sparc_ServerClassMachine(void) {
+  jboolean            result            = JNI_FALSE;
+  /* How big is a server class machine? */
+  const unsigned long server_processors = 2UL;
+  const uint64_t      server_memory     = 2UL * GB;
+  const uint64_t      actual_memory     = physical_memory();
+
+  /* Is this a server class machine? */
+  if (actual_memory >= server_memory) {
+    const unsigned long actual_processors = physical_processors();
+    if (actual_processors >= server_processors) {
+      result = JNI_TRUE;
+    }
+  }
+  if (_launcher_debug) {
+    printf("solaris_" ARCH "_ServerClassMachine: %s\n",
+           (result == JNI_TRUE ? "JNI_TRUE" : "JNI_FALSE"));
+  }
+  return result;
+}
+
+#endif /* __sun && __sparc */
+
+#if defined(__sun) && defined(i586)
+
+/*
+ * A utility method for asking the CPU about itself.
+ * There's a corresponding version of linux-i586
+ * because the compilers are different.
+ */
+void
+get_cpuid(uint32_t arg,
+          uint32_t* eaxp,
+          uint32_t* ebxp,
+          uint32_t* ecxp,
+          uint32_t* edxp) {
+#ifdef _LP64
+  asm(
+  /* rbx is a callee-saved register */
+      " movq    %rbx, %r11  \n"
+  /* rdx and rcx are 3rd and 4th argument registers */
+      " movq    %rdx, %r10  \n"
+      " movq    %rcx, %r9   \n"
+      " movl    %edi, %eax  \n"
+      " cpuid               \n"
+      " movl    %eax, (%rsi)\n"
+      " movl    %ebx, (%r10)\n"
+      " movl    %ecx, (%r9) \n"
+      " movl    %edx, (%r8) \n"
+  /* Restore rbx */
+      " movq    %r11, %rbx");
+#else
+  /* EBX is a callee-saved register */
+  asm(" pushl   %ebx");
+  /* Need ESI for storing through arguments */
+  asm(" pushl   %esi");
+  asm(" movl    8(%ebp), %eax   \n"
+      " cpuid                   \n"
+      " movl    12(%ebp), %esi  \n"
+      " movl    %eax, (%esi)    \n"
+      " movl    16(%ebp), %esi  \n"
+      " movl    %ebx, (%esi)    \n"
+      " movl    20(%ebp), %esi  \n"
+      " movl    %ecx, (%esi)    \n"
+      " movl    24(%ebp), %esi  \n"
+      " movl    %edx, (%esi)      ");
+  /* Restore ESI and EBX */
+  asm(" popl    %esi");
+  /* Restore EBX */
+  asm(" popl    %ebx");
+#endif
+}
+
+#endif /* __sun && i586 */
+
+#if defined(__linux__) && defined(i586)
+
+/*
+ * A utility method for asking the CPU about itself.
+ * There's a corresponding version of solaris-i586
+ * because the compilers are different.
+ */
+void
+get_cpuid(uint32_t arg,
+          uint32_t* eaxp,
+          uint32_t* ebxp,
+          uint32_t* ecxp,
+          uint32_t* edxp) {
+#ifdef _LP64
+  __asm__ volatile (/* Instructions */
+                    "   movl    %4, %%eax  \n"
+                    "   cpuid              \n"
+                    "   movl    %%eax, (%0)\n"
+                    "   movl    %%ebx, (%1)\n"
+                    "   movl    %%ecx, (%2)\n"
+                    "   movl    %%edx, (%3)\n"
+                    : /* Outputs */
+                    : /* Inputs */
+                    "r" (eaxp),
+                    "r" (ebxp),
+                    "r" (ecxp),
+                    "r" (edxp),
+                    "r" (arg)
+                    : /* Clobbers */
+                    "%rax", "%rbx", "%rcx", "%rdx", "memory"
+                    );
+#else
+  uint32_t value_of_eax = 0;
+  uint32_t value_of_ebx = 0;
+  uint32_t value_of_ecx = 0;
+  uint32_t value_of_edx = 0;
+  __asm__ volatile (/* Instructions */
+                        /* ebx is callee-save, so push it */
+                        /* even though it's in the clobbers section */
+                    "   pushl   %%ebx      \n"
+                    "   movl    %4, %%eax  \n"
+                    "   cpuid              \n"
+                    "   movl    %%eax, %0  \n"
+                    "   movl    %%ebx, %1  \n"
+                    "   movl    %%ecx, %2  \n"
+                    "   movl    %%edx, %3  \n"
+                        /* restore ebx */
+                    "   popl    %%ebx      \n"
+
+                    : /* Outputs */
+                    "=m" (value_of_eax),
+                    "=m" (value_of_ebx),
+                    "=m" (value_of_ecx),
+                    "=m" (value_of_edx)
+                    : /* Inputs */
+                    "m" (arg)
+                    : /* Clobbers */
+                    "%eax", "%ebx", "%ecx", "%edx"
+                    );
+  *eaxp = value_of_eax;
+  *ebxp = value_of_ebx;
+  *ecxp = value_of_ecx;
+  *edxp = value_of_edx;
+#endif
+}
+
+#endif /* __linux__ && i586 */
+
+#ifdef i586
+/*
+ * Routines shared by solaris-i586 and linux-i586.
+ */
+
+enum HyperThreadingSupport_enum {
+  hts_supported        =  1,
+  hts_too_soon_to_tell =  0,
+  hts_not_supported    = -1,
+  hts_not_pentium4     = -2,
+  hts_not_intel        = -3
+};
+typedef enum HyperThreadingSupport_enum HyperThreadingSupport;
+
+/* Determine if hyperthreading is supported */
+HyperThreadingSupport
+hyperthreading_support(void) {
+  HyperThreadingSupport result = hts_too_soon_to_tell;
+  /* Bits 11 through 8 is family processor id */
+# define FAMILY_ID_SHIFT 8
+# define FAMILY_ID_MASK 0xf
+  /* Bits 23 through 20 is extended family processor id */
+# define EXT_FAMILY_ID_SHIFT 20
+# define EXT_FAMILY_ID_MASK 0xf
+  /* Pentium 4 family processor id */
+# define PENTIUM4_FAMILY_ID 0xf
+  /* Bit 28 indicates Hyper-Threading Technology support */
+# define HT_BIT_SHIFT 28
+# define HT_BIT_MASK 1
+  uint32_t vendor_id[3] = { 0U, 0U, 0U };
+  uint32_t value_of_eax = 0U;
+  uint32_t value_of_edx = 0U;
+  uint32_t dummy        = 0U;
+
+  /* Yes, this is supposed to be [0], [2], [1] */
+  get_cpuid(0, &dummy, &vendor_id[0], &vendor_id[2], &vendor_id[1]);
+  if (_launcher_debug) {
+    printf("vendor: %c %c %c %c %c %c %c %c %c %c %c %c \n",
+           ((vendor_id[0] >>  0) & 0xff),
+           ((vendor_id[0] >>  8) & 0xff),
+           ((vendor_id[0] >> 16) & 0xff),
+           ((vendor_id[0] >> 24) & 0xff),
+           ((vendor_id[1] >>  0) & 0xff),
+           ((vendor_id[1] >>  8) & 0xff),
+           ((vendor_id[1] >> 16) & 0xff),
+           ((vendor_id[1] >> 24) & 0xff),
+           ((vendor_id[2] >>  0) & 0xff),
+           ((vendor_id[2] >>  8) & 0xff),
+           ((vendor_id[2] >> 16) & 0xff),
+           ((vendor_id[2] >> 24) & 0xff));
+  }
+  get_cpuid(1, &value_of_eax, &dummy, &dummy, &value_of_edx);
+  if (_launcher_debug) {
+    printf("value_of_eax: 0x%x  value_of_edx: 0x%x\n",
+           value_of_eax, value_of_edx);
+  }
+  if ((((value_of_eax >> FAMILY_ID_SHIFT) & FAMILY_ID_MASK) == PENTIUM4_FAMILY_ID) ||
+      (((value_of_eax >> EXT_FAMILY_ID_SHIFT) & EXT_FAMILY_ID_MASK) != 0)) {
+    if ((((vendor_id[0] >>  0) & 0xff) == 'G') &&
+        (((vendor_id[0] >>  8) & 0xff) == 'e') &&
+        (((vendor_id[0] >> 16) & 0xff) == 'n') &&
+        (((vendor_id[0] >> 24) & 0xff) == 'u') &&
+        (((vendor_id[1] >>  0) & 0xff) == 'i') &&
+        (((vendor_id[1] >>  8) & 0xff) == 'n') &&
+        (((vendor_id[1] >> 16) & 0xff) == 'e') &&
+        (((vendor_id[1] >> 24) & 0xff) == 'I') &&
+        (((vendor_id[2] >>  0) & 0xff) == 'n') &&
+        (((vendor_id[2] >>  8) & 0xff) == 't') &&
+        (((vendor_id[2] >> 16) & 0xff) == 'e') &&
+        (((vendor_id[2] >> 24) & 0xff) == 'l')) {
+      if (((value_of_edx >> HT_BIT_SHIFT) & HT_BIT_MASK) == HT_BIT_MASK) {
+        if (_launcher_debug) {
+          printf("Hyperthreading supported\n");
+        }
+        result = hts_supported;
+      } else {
+        if (_launcher_debug) {
+          printf("Hyperthreading not supported\n");
+        }
+        result = hts_not_supported;
+      }
+    } else {
+      if (_launcher_debug) {
+        printf("Not GenuineIntel\n");
+      }
+      result = hts_not_intel;
+    }
+  } else {
+    if (_launcher_debug) {
+      printf("not Pentium 4 or extended\n");
+    }
+    result = hts_not_pentium4;
+  }
+  return result;
+}
+
+/* Determine how many logical processors there are per CPU */
+unsigned int
+logical_processors_per_package(void) {
+  /*
+   * After CPUID with EAX==1, register EBX bits 23 through 16
+   * indicate the number of logical processors per package
+   */
+# define NUM_LOGICAL_SHIFT 16
+# define NUM_LOGICAL_MASK 0xff
+  unsigned int result                        = 1U;
+  const HyperThreadingSupport hyperthreading = hyperthreading_support();
+
+  if (hyperthreading == hts_supported) {
+    uint32_t value_of_ebx = 0U;
+    uint32_t dummy        = 0U;
+
+    get_cpuid(1, &dummy, &value_of_ebx, &dummy, &dummy);
+    result = (value_of_ebx >> NUM_LOGICAL_SHIFT) & NUM_LOGICAL_MASK;
+    if (_launcher_debug) {
+      printf("logical processors per package: %u\n", result);
+    }
+  }
+  return result;
+}
+
+/* Compute the number of physical processors, not logical processors */
+unsigned long
+physical_processors(void) {
+  const long sys_processors = sysconf(_SC_NPROCESSORS_CONF);
+  unsigned long result      = sys_processors;
+
+  if (_launcher_debug) {
+    printf("sysconf(_SC_NPROCESSORS_CONF): %lu\n", sys_processors);
+  }
+  if (sys_processors > 1) {
+    unsigned int logical_processors = logical_processors_per_package();
+    if (logical_processors > 1) {
+      result = (unsigned long) sys_processors / logical_processors;
+    }
+  }
+  if (_launcher_debug) {
+    printf("physical processors: %lu\n", result);
+  }
+  return result;
+}
+
+#endif /* i586 */
+
+#if defined(__sun) && defined(i586)
+
+/* The definition of a server-class machine for solaris-i586/amd64 */
+jboolean
+solaris_i586_ServerClassMachine(void) {
+  jboolean            result            = JNI_FALSE;
+  /* How big is a server class machine? */
+  const unsigned long server_processors = 2UL;
+  const uint64_t      server_memory     = 2UL * GB;
+  /*
+   * We seem not to get our full complement of memory.
+   *     We allow some part (1/8?) of the memory to be "missing",
+   *     based on the sizes of DIMMs, and maybe graphics cards.
+   */
+  const uint64_t      missing_memory    = 256UL * MB;
+  const uint64_t      actual_memory     = physical_memory();
+
+  /* Is this a server class machine? */
+  if (actual_memory >= (server_memory - missing_memory)) {
+    const unsigned long actual_processors = physical_processors();
+    if (actual_processors >= server_processors) {
+      result = JNI_TRUE;
+    }
+  }
+  if (_launcher_debug) {
+    printf("solaris_" ARCH "_ServerClassMachine: %s\n",
+           (result == JNI_TRUE ? "true" : "false"));
+  }
+  return result;
+}
+
+#endif /* __sun && i586 */
+
+#if defined(__linux__) && defined(i586)
+
+/* The definition of a server-class machine for linux-i586 */
+jboolean
+linux_i586_ServerClassMachine(void) {
+  jboolean            result            = JNI_FALSE;
+  /* How big is a server class machine? */
+  const unsigned long server_processors = 2UL;
+  const uint64_t      server_memory     = 2UL * GB;
+  /*
+   * We seem not to get our full complement of memory.
+   *     We allow some part (1/8?) of the memory to be "missing",
+   *     based on the sizes of DIMMs, and maybe graphics cards.
+   */
+  const uint64_t      missing_memory    = 256UL * MB;
+  const uint64_t      actual_memory     = physical_memory();
+
+  /* Is this a server class machine? */
+  if (actual_memory >= (server_memory - missing_memory)) {
+    const unsigned long actual_processors = physical_processors();
+    if (actual_processors >= server_processors) {
+      result = JNI_TRUE;
+    }
+  }
+  if (_launcher_debug) {
+    printf("linux_" ARCH "_ServerClassMachine: %s\n",
+           (result == JNI_TRUE ? "true" : "false"));
+  }
+  return result;
+}
+
+#endif /* __linux__ && i586 */
+
+/* Dispatch to the platform-specific definition of "server-class" */
+jboolean
+ServerClassMachine(void) {
+  jboolean result = JNI_FALSE;
+#if   defined(__sun) && defined(__sparc)
+  result = solaris_sparc_ServerClassMachine();
+#elif defined(__sun) && defined(i586)
+  result = solaris_i586_ServerClassMachine();
+#elif defined(__linux__) && defined(i586)
+  result = linux_i586_ServerClassMachine();
+#else
+  if (_launcher_debug) {
+    printf("ServerClassMachine: returns default value of %s\n",
+           (result == JNI_TRUE ? "true" : "false"));
+  }
+#endif
+  return result;
+}
+
+#endif /* ifndef GAMMA */
+
+#ifndef GAMMA /* gamma launcher does not choose JDK/JRE/JVM */
+
+/*
+ *      Since using the file system as a registry is a bit risky, perform
+ *      additional sanity checks on the identified directory to validate
+ *      it as a valid jre/sdk.
+ *
+ *      Return 0 if the tests fail; otherwise return non-zero (true).
+ *
+ *      Note that checking for anything more than the existence of an
+ *      executable object at bin/java relative to the path being checked
+ *      will break the regression tests.
+ */
+static int
+CheckSanity(char *path, char *dir)
+{
+    char    buffer[PATH_MAX];
+
+    if (strlen(path) + strlen(dir) + 11 > PATH_MAX)
+        return (0);     /* Silently reject "impossibly" long paths */
+
+    (void)strcat(strcat(strcat(strcpy(buffer, path), "/"), dir), "/bin/java");
+    return ((access(buffer, X_OK) == 0) ? 1 : 0);
+}
+
+/*
+ *      Determine if there is an acceptable JRE in the directory dirname.
+ *      Upon locating the "best" one, return a fully qualified path to
+ *      it. "Best" is defined as the most advanced JRE meeting the
+ *      constraints contained in the manifest_info. If no JRE in this
+ *      directory meets the constraints, return NULL.
+ *
+ *      Note that we don't check for errors in reading the directory
+ *      (which would be done by checking errno).  This is because it
+ *      doesn't matter if we get an error reading the directory, or
+ *      we just don't find anything interesting in the directory.  We
+ *      just return NULL in either case.
+ *
+ *      The historical names of j2sdk and j2re were changed to jdk and
+ *      jre respecively as part of the 1.5 rebranding effort.  Since the
+ *      former names are legacy on Linux, they must be recognized for
+ *      all time.  Fortunately, this is a minor cost.
+ */
+static char
+*ProcessDir(manifest_info *info, char *dirname)
+{
+    DIR     *dirp;
+    struct dirent *dp;
+    char    *best = NULL;
+    int     offset;
+    int     best_offset = 0;
+    char    *ret_str = NULL;
+    char    buffer[PATH_MAX];
+
+    if ((dirp = opendir(dirname)) == NULL)
+        return (NULL);
+
+    do {
+        if ((dp = readdir(dirp)) != NULL) {
+            offset = 0;
+            if ((strncmp(dp->d_name, "jre", 3) == 0) ||
+                (strncmp(dp->d_name, "jdk", 3) == 0))
+                offset = 3;
+            else if (strncmp(dp->d_name, "j2re", 4) == 0)
+                offset = 4;
+            else if (strncmp(dp->d_name, "j2sdk", 5) == 0)
+                offset = 5;
+            if (offset > 0) {
+                if ((acceptable_release(dp->d_name + offset,
+                    info->jre_version)) && CheckSanity(dirname, dp->d_name))
+                    if ((best == NULL) || (exact_version_id(
+                      dp->d_name + offset, best + best_offset) > 0)) {
+                        if (best != NULL)
+                            free(best);
+                        best = strdup(dp->d_name);
+                        best_offset = offset;
+                    }
+            }
+        }
+    } while (dp != NULL);
+    (void) closedir(dirp);
+    if (best == NULL)
+        return (NULL);
+    else {
+        ret_str = MemAlloc(strlen(dirname) + strlen(best) + 2);
+        ret_str = strcat(strcat(strcpy(ret_str, dirname), "/"), best);
+        free(best);
+        return (ret_str);
+    }
+}
+
+/*
+ *      This is the global entry point. It examines the host for the optimal
+ *      JRE to be used by scanning a set of directories.  The set of directories
+ *      is platform dependent and can be overridden by the environment
+ *      variable JAVA_VERSION_PATH.
+ *
+ *      This routine itself simply determines the set of appropriate
+ *      directories before passing control onto ProcessDir().
+ */
+char*
+LocateJRE(manifest_info* info)
+{
+    char        *path;
+    char        *home;
+    char        *target = NULL;
+    char        *dp;
+    char        *cp;
+
+    /*
+     * Start by getting JAVA_VERSION_PATH
+     */
+    if (info->jre_restrict_search)
+        path = strdup(system_dir);
+    else if ((path = getenv("JAVA_VERSION_PATH")) != NULL)
+        path = strdup(path);
+    else
+        if ((home = getenv("HOME")) != NULL) {
+            path = (char *)MemAlloc(strlen(home) + 13);
+            path = strcat(strcat(strcat(strcpy(path, home),
+                user_dir), ":"), system_dir);
+        } else
+            path = strdup(system_dir);
+
+    /*
+     * Step through each directory on the path. Terminate the scan with
+     * the first directory with an acceptable JRE.
+     */
+    cp = dp = path;
+    while (dp != NULL) {
+        cp = strchr(dp, (int)':');
+        if (cp != NULL)
+            *cp = (char)NULL;
+        if ((target = ProcessDir(info, dp)) != NULL)
+            break;
+        dp = cp;
+        if (dp != NULL)
+            dp++;
+    }
+    free(path);
+    return (target);
+}
+
+/*
+ * Given a path to a jre to execute, this routine checks if this process
+ * is indeed that jre.  If not, it exec's that jre.
+ *
+ * We want to actually check the paths rather than just the version string
+ * built into the executable, so that given version specification (and
+ * JAVA_VERSION_PATH) will yield the exact same Java environment, regardless
+ * of the version of the arbitrary launcher we start with.
+ */
+void
+ExecJRE(char *jre, char **argv)
+{
+    char    wanted[PATH_MAX];
+    char    *execname;
+    char    *progname;
+
+    /*
+     * Resolve the real path to the directory containing the selected JRE.
+     */
+    if (realpath(jre, wanted) == NULL) {
+        fprintf(stderr, "Unable to resolve %s\n", jre);
+        exit(1);
+    }
+
+    /*
+     * Resolve the real path to the currently running launcher.
+     */
+    execname = SetExecname(argv);
+    if (execname == NULL) {
+        fprintf(stderr, "Unable to resolve current executable\n");
+        exit(1);
+    }
+
+    /*
+     * If the path to the selected JRE directory is a match to the initial
+     * portion of the path to the currently executing JRE, we have a winner!
+     * If so, just return.
+     */
+    if (strncmp(wanted, execname, strlen(wanted)) == 0)
+        return;                 /* I am the droid you were looking for */
+
+    /*
+     * If this isn't the selected version, exec the selected version.
+     */
+#ifdef JAVA_ARGS  /* javac, jar and friends. */
+    progname = "java";
+#else             /* java, oldjava, javaw and friends */
+#ifdef PROGNAME
+    progname = PROGNAME;
+#else
+    progname = *argv;
+    if ((s = strrchr(progname, FILE_SEPARATOR)) != 0) {
+        progname = s + 1;
+    }
+#endif /* PROGNAME */
+#endif /* JAVA_ARGS */
+
+    /*
+     * This should never happen (because of the selection code in SelectJRE),
+     * but check for "impossibly" long path names just because buffer overruns
+     * can be so deadly.
+     */
+    if (strlen(wanted) + strlen(progname) + 6 > PATH_MAX) {
+        fprintf(stderr, "Path length exceeds maximum length (PATH_MAX)\n");
+        exit(1);
+    }
+
+    /*
+     * Construct the path and exec it.
+     */
+    (void)strcat(strcat(wanted, "/bin/"), progname);
+    argv[0] = progname;
+    if (_launcher_debug) {
+        int i;
+        printf("execv(\"%s\"", wanted);
+        for (i = 0; argv[i] != NULL; i++)
+            printf(", \"%s\"", argv[i]);
+        printf(")\n");
+    }
+    execv(wanted, argv);
+    fprintf(stderr, "Exec of %s failed\n", wanted);
+    exit(1);
+}
+
+#endif /* ifndef GAMMA */
+
+/*
+ * "Borrowed" from Solaris 10 where the unsetenv() function is being added
+ * to libc thanks to SUSv3 (Standard Unix Specification, version 3). As
+ * such, in the fullness of time this will appear in libc on all relevant
+ * Solaris/Linux platforms and maybe even the Windows platform.  At that
+ * time, this stub can be removed.
+ *
+ * This implementation removes the environment locking for multithreaded
+ * applications.  (We don't have access to these mutexes within libc and
+ * the launcher isn't multithreaded.)  Note that what remains is platform
+ * independent, because it only relies on attributes that a POSIX environment
+ * defines.
+ *
+ * Returns 0 on success, -1 on failure.
+ *
+ * Also removed was the setting of errno.  The only value of errno set
+ * was EINVAL ("Invalid Argument").
+ */
+
+/*
+ * s1(environ) is name=value
+ * s2(name) is name(not the form of name=value).
+ * if names match, return value of 1, else return 0
+ */
+static int
+match_noeq(const char *s1, const char *s2)
+{
+        while (*s1 == *s2++) {
+                if (*s1++ == '=')
+                        return (1);
+        }
+        if (*s1 == '=' && s2[-1] == '\0')
+                return (1);
+        return (0);
+}
+
+/*
+ * added for SUSv3 standard
+ *
+ * Delete entry from environ.
+ * Do not free() memory!  Other threads may be using it.
+ * Keep it around forever.
+ */
+static int
+borrowed_unsetenv(const char *name)
+{
+        long    idx;            /* index into environ */
+
+        if (name == NULL || *name == '\0' ||
+            strchr(name, '=') != NULL) {
+                return (-1);
+        }
+
+        for (idx = 0; environ[idx] != NULL; idx++) {
+                if (match_noeq(environ[idx], name))
+                        break;
+        }
+        if (environ[idx] == NULL) {
+                /* name not found but still a success */
+                return (0);
+        }
+        /* squeeze up one entry */
+        do {
+                environ[idx] = environ[idx+1];
+        } while (environ[++idx] != NULL);
+
+        return (0);
+}
+/* --- End of "borrowed" code --- */
+
+/*
+ * Wrapper for unsetenv() function.
+ */
+int
+UnsetEnv(char *name)
+{
+    return(borrowed_unsetenv(name));
+}
+/*
+ * The implementation for finding classes from the bootstrap
+ * class loader, refer to java.h
+ */
+static FindClassFromBootLoader_t *findBootClass = NULL;
+
+jclass
+FindBootStrapClass(JNIEnv *env, const char* classname)
+{
+   if (findBootClass == NULL) {
+       findBootClass = (FindClassFromBootLoader_t *)dlsym(RTLD_DEFAULT,
+          "JVM_FindClassFromBootLoader");
+       if (findBootClass == NULL) {
+           fprintf(stderr, "Error: could load method JVM_FindClassFromBootLoader");
+           return NULL;
+       }
+   }
+   return findBootClass(env, classname, JNI_FALSE);
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/os/haiku/launcher/java_md.h	Fri Oct 23 10:48:33 2009 -0700
@@ -0,0 +1,79 @@
+/*
+ * Copyright 1999-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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
+ * published by the Free Software Foundation.
+ *
+ * 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.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+/*
+ * Gamma (Hotspot internal engineering test) launcher based on 1.6.0-b28 JDK,
+ * search "GAMMA" for gamma specific changes.
+ */
+
+#ifndef JAVA_MD_H
+#define JAVA_MD_H
+
+#include <limits.h>
+#include <unistd.h>
+#include <sys/param.h>
+#ifndef GAMMA
+#include "manifest_info.h"
+#endif
+
+#define PATH_SEPARATOR          ':'
+#define FILESEP                 "/"
+#define FILE_SEPARATOR          '/'
+#ifndef MAXNAMELEN
+#define MAXNAMELEN              PATH_MAX
+#endif
+
+#ifdef JAVA_ARGS
+/*
+ * ApplicationHome is prepended to each of these entries; the resulting
+ * strings are concatenated (separated by PATH_SEPARATOR) and used as the
+ * value of -cp option to the launcher.
+ */
+#ifndef APP_CLASSPATH
+#define APP_CLASSPATH        { "/lib/tools.jar", "/classes" }
+#endif
+#endif
+
+#ifdef HAVE_GETHRTIME
+/*
+ * Support for doing cheap, accurate interval timing.
+ */
+#include <sys/time.h>
+#define CounterGet()              (gethrtime()/1000)
+#define Counter2Micros(counts)    (counts)
+#else
+#define CounterGet()              (system_time())
+#define Counter2Micros(counts)    (counts)
+#endif /* HAVE_GETHRTIME */
+
+/*
+ * Function prototypes.
+ */
+#ifndef GAMMA
+char *LocateJRE(manifest_info* info);
+void ExecJRE(char *jre, char **argv);
+#endif
+int UnsetEnv(char *name);
+
+#endif