1 /*
   2  * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * Shared source for 'java' command line tool.
  28  *
  29  * If JAVA_ARGS is defined, then acts as a launcher for applications. For
  30  * instance, the JDK command line tools such as javac and javadoc (see
  31  * makefiles for more details) are built with this program.  Any arguments
  32  * prefixed with '-J' will be passed directly to the 'java' command.
  33  */
  34 
  35 /*
  36  * One job of the launcher is to remove command line options which the
  37  * vm does not understand and will not process.  These options include
  38  * options which select which style of vm is run (e.g. -client and
  39  * -server) as well as options which select the data model to use.
  40  * Additionally, for tools which invoke an underlying vm "-J-foo"
  41  * options are turned into "-foo" options to the vm.  This option
  42  * filtering is handled in a number of places in the launcher, some of
  43  * it in machine-dependent code.  In this file, the function
  44  * CheckJvmType removes vm style options and TranslateApplicationArgs
  45  * removes "-J" prefixes.  The CreateExecutionEnvironment function processes
  46  * and removes -d<n> options. On unix, there is a possibility that the running
  47  * data model may not match to the desired data model, in this case an exec is
  48  * required to start the desired model. If the data models match, then
  49  * ParseArguments will remove the -d<n> flags. If the data models do not match
  50  * the CreateExecutionEnviroment will remove the -d<n> flags.
  51  */
  52 
  53 
  54 #include "java.h"
  55 
  56 /*
  57  * A NOTE TO DEVELOPERS: For performance reasons it is important that
  58  * the program image remain relatively small until after SelectVersion
  59  * CreateExecutionEnvironment have finished their possibly recursive
  60  * processing. Watch everything, but resist all temptations to use Java
  61  * interfaces.
  62  */
  63 
  64 /* we always print to stderr */
  65 #define USE_STDERR JNI_TRUE
  66 
  67 static jboolean printVersion = JNI_FALSE; /* print and exit */
  68 static jboolean showVersion = JNI_FALSE;  /* print but continue */
  69 static jboolean printUsage = JNI_FALSE;   /* print and exit*/
  70 static jboolean printXUsage = JNI_FALSE;  /* print and exit*/
  71 static char     *showSettings = NULL;      /* print but continue */
  72 static char     *listModules = NULL;
  73 
  74 static const char *_program_name;
  75 static const char *_launcher_name;
  76 static jboolean _is_java_args = JNI_FALSE;
  77 static jboolean _have_classpath = JNI_FALSE;
  78 static const char *_fVersion;
  79 static jboolean _wc_enabled = JNI_FALSE;
  80 static jint _ergo_policy = DEFAULT_POLICY;
  81 
  82 /*
  83  * Entries for splash screen environment variables.
  84  * putenv is performed in SelectVersion. We need
  85  * them in memory until UnsetEnv, so they are made static
  86  * global instead of auto local.
  87  */
  88 static char* splash_file_entry = NULL;
  89 static char* splash_jar_entry = NULL;
  90 
  91 /*
  92  * List of VM options to be specified when the VM is created.
  93  */
  94 static JavaVMOption *options;
  95 static int numOptions, maxOptions;
  96 
  97 /*
  98  * Prototypes for functions internal to launcher.
  99  */
 100 static void SetClassPath(const char *s);
 101 static void SetModulePath(const char *s);
 102 static void SetUpgradeModulePath(const char *s);
 103 static void SetMainModule(const char *s);
 104 static void SetAddModulesProp(const char *mods);
 105 static void SetLimitModulesProp(const char *mods);
 106 static void SetAddReadsProp(const jint n, const char *s);
 107 static void SetAddExportsProp(const jint n, const char *s);
 108 static void SetPatchProp(const jint n, const char *s);
 109 static void SelectVersion(int argc, char **argv, char **main_class);
 110 static void SetJvmEnvironment(int argc, char **argv);
 111 static jboolean ParseArguments(int *pargc, char ***pargv,
 112                                int *pmode, char **pwhat,
 113                                int *pret, const char *jrepath);
 114 static jboolean InitializeJVM(JavaVM **pvm, JNIEnv **penv,
 115                               InvocationFunctions *ifn);
 116 static jstring NewPlatformString(JNIEnv *env, char *s);
 117 static jclass LoadMainClass(JNIEnv *env, int mode, char *name);
 118 static jclass GetApplicationClass(JNIEnv *env);
 119 
 120 static void TranslateApplicationArgs(int jargc, const char **jargv, int *pargc, char ***pargv);
 121 static jboolean AddApplicationOptions(int cpathc, const char **cpathv);
 122 static void SetApplicationClassPath(const char**);
 123 
 124 static void PrintJavaVersion(JNIEnv *env, jboolean extraLF);
 125 static void PrintUsage(JNIEnv* env, jboolean doXUsage);
 126 static void ShowSettings(JNIEnv* env, char *optString);
 127 static void ListModules(JNIEnv* env, char *optString);
 128 static void SetNativeThreadName(JNIEnv* env, char *name);
 129 
 130 static void SetPaths(int argc, char **argv);
 131 
 132 static void DumpState();
 133 static jboolean RemovableOption(char *option);
 134 
 135 /* Maximum supported entries from jvm.cfg. */
 136 #define INIT_MAX_KNOWN_VMS      10
 137 
 138 /* Values for vmdesc.flag */
 139 enum vmdesc_flag {
 140     VM_UNKNOWN = -1,
 141     VM_KNOWN,
 142     VM_ALIASED_TO,
 143     VM_WARN,
 144     VM_ERROR,
 145     VM_IF_SERVER_CLASS,
 146     VM_IGNORE
 147 };
 148 
 149 struct vmdesc {
 150     char *name;
 151     int flag;
 152     char *alias;
 153     char *server_class;
 154 };
 155 static struct vmdesc *knownVMs = NULL;
 156 static int knownVMsCount = 0;
 157 static int knownVMsLimit = 0;
 158 
 159 static void GrowKnownVMs(int minimum);
 160 static int  KnownVMIndex(const char* name);
 161 static void FreeKnownVMs();
 162 static jboolean IsWildCardEnabled();
 163 
 164 #define ARG_CHECK(AC_arg_count, AC_failure_message, AC_questionable_arg) \
 165     do { \
 166         if (AC_arg_count < 1) { \
 167             JLI_ReportErrorMessage(AC_failure_message, AC_questionable_arg); \
 168             printUsage = JNI_TRUE; \
 169             *pret = 1; \
 170             return JNI_TRUE; \
 171         } \
 172     } while (JNI_FALSE)
 173 
 174 /*
 175  * Running Java code in primordial thread caused many problems. We will
 176  * create a new thread to invoke JVM. See 6316197 for more information.
 177  */
 178 static jlong threadStackSize    = 0;  /* stack size of the new thread */
 179 static jlong maxHeapSize        = 0;  /* max heap size */
 180 static jlong initialHeapSize    = 0;  /* inital heap size */
 181 
 182 /*
 183  * A minimum -Xss stack size suitable for all platforms.
 184  */
 185 #ifndef STACK_SIZE_MINIMUM
 186 #define STACK_SIZE_MINIMUM (32 * KB)
 187 #endif
 188 
 189 /*
 190  * Entry point.
 191  */
 192 int
 193 JLI_Launch(int argc, char ** argv,              /* main argc, argc */
 194         int jargc, const char** jargv,          /* java args */
 195         int appclassc, const char** appclassv,  /* app classpath */
 196         const char* fullversion,                /* full version defined */
 197         const char* dotversion,                 /* UNUSED dot version defined */
 198         const char* pname,                      /* program name */
 199         const char* lname,                      /* launcher name */
 200         jboolean javaargs,                      /* JAVA_ARGS */
 201         jboolean cpwildcard,                    /* classpath wildcard*/
 202         jboolean javaw,                         /* windows-only javaw */
 203         jint ergo                               /* ergonomics class policy */
 204 )
 205 {
 206     int mode = LM_UNKNOWN;
 207     char *what = NULL;
 208     char *main_class = NULL;
 209     int ret;
 210     InvocationFunctions ifn;
 211     jlong start, end;
 212     char jvmpath[MAXPATHLEN];
 213     char jrepath[MAXPATHLEN];
 214     char jvmcfg[MAXPATHLEN];
 215 
 216     _fVersion = fullversion;
 217     _launcher_name = lname;
 218     _program_name = pname;
 219     _is_java_args = javaargs;
 220     _wc_enabled = cpwildcard;
 221     _ergo_policy = ergo;
 222 
 223     InitLauncher(javaw);
 224     DumpState();
 225     if (JLI_IsTraceLauncher()) {
 226         int i;
 227         printf("Command line args:\n");
 228         for (i = 0; i < argc ; i++) {
 229             printf("argv[%d] = %s\n", i, argv[i]);
 230         }
 231         AddOption("-Dsun.java.launcher.diag=true", NULL);
 232     }
 233 
 234     /*
 235      * SelectVersion() has several responsibilities:
 236      *
 237      *  1) Disallow specification of another JRE.  With 1.9, another
 238      *     version of the JRE cannot be invoked.
 239      *  2) Allow for a JRE version to invoke JDK 1.9 or later.  Since
 240      *     all mJRE directives have been stripped from the request but
 241      *     the pre 1.9 JRE [ 1.6 thru 1.8 ], it is as if 1.9+ has been
 242      *     invoked from the command line.
 243      */
 244     SelectVersion(argc, argv, &main_class);
 245 
 246     CreateExecutionEnvironment(&argc, &argv,
 247                                jrepath, sizeof(jrepath),
 248                                jvmpath, sizeof(jvmpath),
 249                                jvmcfg,  sizeof(jvmcfg));
 250 
 251     if (!IsJavaArgs()) {
 252         SetJvmEnvironment(argc,argv);
 253     }
 254 
 255     ifn.CreateJavaVM = 0;
 256     ifn.GetDefaultJavaVMInitArgs = 0;
 257 
 258     if (JLI_IsTraceLauncher()) {
 259         start = CounterGet();
 260     }
 261 
 262     if (!LoadJavaVM(jvmpath, &ifn)) {
 263         return(6);
 264     }
 265 
 266     if (JLI_IsTraceLauncher()) {
 267         end   = CounterGet();
 268     }
 269 
 270     JLI_TraceLauncher("%ld micro seconds to LoadJavaVM\n",
 271              (long)(jint)Counter2Micros(end-start));
 272 
 273     ++argv;
 274     --argc;
 275 
 276     if (IsJavaArgs()) {
 277         /* Preprocess wrapper arguments */
 278         TranslateApplicationArgs(jargc, jargv, &argc, &argv);
 279         if (!AddApplicationOptions(appclassc, appclassv)) {
 280             return(1);
 281         }
 282     } else {
 283         /* Set default CLASSPATH */
 284         char* cpath = getenv("CLASSPATH");
 285         if (cpath != NULL) {
 286             SetClassPath(cpath);
 287         }
 288     }
 289 
 290     /* Parse command line options; if the return value of
 291      * ParseArguments is false, the program should exit.
 292      */
 293     if (!ParseArguments(&argc, &argv, &mode, &what, &ret, jrepath))
 294     {
 295         return(ret);
 296     }
 297 
 298     /* Override class path if -jar flag was specified */
 299     if (mode == LM_JAR) {
 300         SetClassPath(what);     /* Override class path */
 301     }
 302 
 303     /* set the -Dsun.java.command pseudo property */
 304     SetJavaCommandLineProp(what, argc, argv);
 305 
 306     /* Set the -Dsun.java.launcher pseudo property */
 307     SetJavaLauncherProp();
 308 
 309     /* set the -Dsun.java.launcher.* platform properties */
 310     SetJavaLauncherPlatformProps();
 311 
 312     return JVMInit(&ifn, threadStackSize, argc, argv, mode, what, ret);
 313 }
 314 /*
 315  * Always detach the main thread so that it appears to have ended when
 316  * the application's main method exits.  This will invoke the
 317  * uncaught exception handler machinery if main threw an
 318  * exception.  An uncaught exception handler cannot change the
 319  * launcher's return code except by calling System.exit.
 320  *
 321  * Wait for all non-daemon threads to end, then destroy the VM.
 322  * This will actually create a trivial new Java waiter thread
 323  * named "DestroyJavaVM", but this will be seen as a different
 324  * thread from the one that executed main, even though they are
 325  * the same C thread.  This allows mainThread.join() and
 326  * mainThread.isAlive() to work as expected.
 327  */
 328 #define LEAVE() \
 329     SetNativeThreadName(env, "DestroyJavaVM"); \
 330     if ((*env)->ExceptionOccurred(env)) { \
 331       /* Clear non critical pending exceptions at this point. */ \
 332       (*env)->ExceptionClear(env); \
 333     } \
 334     do { \
 335         if ((*vm)->DetachCurrentThread(vm) != JNI_OK) { \
 336             JLI_ReportErrorMessage(JVM_ERROR2); \
 337             ret = 1; \
 338         } \
 339         if (JNI_TRUE) { \
 340             (*vm)->DestroyJavaVM(vm); \
 341             return ret; \
 342         } \
 343     } while (JNI_FALSE)
 344 
 345 #define CHECK_EXCEPTION_NULL_LEAVE(CENL_exception) \
 346     do { \
 347         if ((*env)->ExceptionOccurred(env)) { \
 348             JLI_ReportExceptionDescription(env); \
 349             LEAVE(); \
 350         } \
 351         if ((CENL_exception) == NULL) { \
 352             JLI_ReportErrorMessage(JNI_ERROR); \
 353             LEAVE(); \
 354         } \
 355     } while (JNI_FALSE)
 356 
 357 #define CHECK_EXCEPTION_LEAVE(CEL_return_value) \
 358     do { \
 359         if ((*env)->ExceptionOccurred(env)) { \
 360             JLI_ReportExceptionDescription(env); \
 361             ret = (CEL_return_value); \
 362             LEAVE(); \
 363         } \
 364     } while (JNI_FALSE)
 365 
 366 
 367 int JNICALL
 368 JavaMain(void * _args)
 369 {
 370     JavaMainArgs *args = (JavaMainArgs *)_args;
 371     int argc = args->argc;
 372     char **argv = args->argv;
 373     int mode = args->mode;
 374     char *what = args->what;
 375     InvocationFunctions ifn = args->ifn;
 376 
 377     JavaVM *vm = 0;
 378     JNIEnv *env = 0;
 379     jclass mainClass = NULL;
 380     jclass appClass = NULL; // actual application class being launched
 381     jmethodID mainID;
 382     jobjectArray mainArgs;
 383     int ret = 0;
 384     jlong start, end;
 385 
 386     RegisterThread();
 387 
 388     /* Initialize the virtual machine */
 389     start = CounterGet();
 390     if (!InitializeJVM(&vm, &env, &ifn)) {
 391         JLI_ReportErrorMessage(JVM_ERROR1);
 392         exit(1);
 393     }
 394 
 395     SetNativeThreadName(env, "main");
 396     if ((*env)->ExceptionOccurred(env)) {
 397       /* Clear non critical pending exceptions at this point. */
 398       (*env)->ExceptionClear(env);
 399     }
 400 
 401     if (showSettings != NULL) {
 402         ShowSettings(env, showSettings);
 403         CHECK_EXCEPTION_LEAVE(1);
 404     }
 405 
 406     if (listModules != NULL) {
 407         ListModules(env, listModules);
 408         CHECK_EXCEPTION_LEAVE(1);
 409         LEAVE();
 410     }
 411 
 412     if (printVersion || showVersion) {
 413         PrintJavaVersion(env, showVersion);
 414         CHECK_EXCEPTION_LEAVE(0);
 415         if (printVersion) {
 416             LEAVE();
 417         }
 418     }
 419 
 420     /* If the user specified neither a class name nor a JAR file */
 421     if (printXUsage || printUsage || what == 0 || mode == LM_UNKNOWN) {
 422         PrintUsage(env, printXUsage);
 423         CHECK_EXCEPTION_LEAVE(1);
 424         LEAVE();
 425     }
 426 
 427     FreeKnownVMs();  /* after last possible PrintUsage() */
 428 
 429     if (JLI_IsTraceLauncher()) {
 430         end = CounterGet();
 431         JLI_TraceLauncher("%ld micro seconds to InitializeJVM\n",
 432                (long)(jint)Counter2Micros(end-start));
 433     }
 434 
 435     /* At this stage, argc/argv have the application's arguments */
 436     if (JLI_IsTraceLauncher()){
 437         int i;
 438         printf("%s is '%s'\n", launchModeNames[mode], what);
 439         printf("App's argc is %d\n", argc);
 440         for (i=0; i < argc; i++) {
 441             printf("    argv[%2d] = '%s'\n", i, argv[i]);
 442         }
 443     }
 444 
 445     ret = 1;
 446 
 447     /*
 448      * Get the application's main class.
 449      *
 450      * See bugid 5030265.  The Main-Class name has already been parsed
 451      * from the manifest, but not parsed properly for UTF-8 support.
 452      * Hence the code here ignores the value previously extracted and
 453      * uses the pre-existing code to reextract the value.  This is
 454      * possibly an end of release cycle expedient.  However, it has
 455      * also been discovered that passing some character sets through
 456      * the environment has "strange" behavior on some variants of
 457      * Windows.  Hence, maybe the manifest parsing code local to the
 458      * launcher should never be enhanced.
 459      *
 460      * Hence, future work should either:
 461      *     1)   Correct the local parsing code and verify that the
 462      *          Main-Class attribute gets properly passed through
 463      *          all environments,
 464      *     2)   Remove the vestages of maintaining main_class through
 465      *          the environment (and remove these comments).
 466      *
 467      * This method also correctly handles launching existing JavaFX
 468      * applications that may or may not have a Main-Class manifest entry.
 469      */
 470     mainClass = LoadMainClass(env, mode, what);
 471     CHECK_EXCEPTION_NULL_LEAVE(mainClass);
 472     /*
 473      * In some cases when launching an application that needs a helper, e.g., a
 474      * JavaFX application with no main method, the mainClass will not be the
 475      * applications own main class but rather a helper class. To keep things
 476      * consistent in the UI we need to track and report the application main class.
 477      */
 478     appClass = GetApplicationClass(env);
 479     NULL_CHECK_RETURN_VALUE(appClass, -1);
 480     /*
 481      * PostJVMInit uses the class name as the application name for GUI purposes,
 482      * for example, on OSX this sets the application name in the menu bar for
 483      * both SWT and JavaFX. So we'll pass the actual application class here
 484      * instead of mainClass as that may be a launcher or helper class instead
 485      * of the application class.
 486      */
 487     PostJVMInit(env, appClass, vm);
 488     CHECK_EXCEPTION_LEAVE(1);
 489     /*
 490      * The LoadMainClass not only loads the main class, it will also ensure
 491      * that the main method's signature is correct, therefore further checking
 492      * is not required. The main method is invoked here so that extraneous java
 493      * stacks are not in the application stack trace.
 494      */
 495     mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
 496                                        "([Ljava/lang/String;)V");
 497     CHECK_EXCEPTION_NULL_LEAVE(mainID);
 498 
 499     /* Build platform specific argument array */
 500     mainArgs = CreateApplicationArgs(env, argv, argc);
 501     CHECK_EXCEPTION_NULL_LEAVE(mainArgs);
 502 
 503     /* Invoke main method. */
 504     (*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);
 505 
 506     /*
 507      * The launcher's exit code (in the absence of calls to
 508      * System.exit) will be non-zero if main threw an exception.
 509      */
 510     ret = (*env)->ExceptionOccurred(env) == NULL ? 0 : 1;
 511     LEAVE();
 512 }
 513 
 514 /*
 515  * Checks the command line options to find which JVM type was
 516  * specified.  If no command line option was given for the JVM type,
 517  * the default type is used.  The environment variable
 518  * JDK_ALTERNATE_VM and the command line option -XXaltjvm= are also
 519  * checked as ways of specifying which JVM type to invoke.
 520  */
 521 char *
 522 CheckJvmType(int *pargc, char ***argv, jboolean speculative) {
 523     int i, argi;
 524     int argc;
 525     char **newArgv;
 526     int newArgvIdx = 0;
 527     int isVMType;
 528     int jvmidx = -1;
 529     char *jvmtype = getenv("JDK_ALTERNATE_VM");
 530 
 531     argc = *pargc;
 532 
 533     /* To make things simpler we always copy the argv array */
 534     newArgv = JLI_MemAlloc((argc + 1) * sizeof(char *));
 535 
 536     /* The program name is always present */
 537     newArgv[newArgvIdx++] = (*argv)[0];
 538 
 539     for (argi = 1; argi < argc; argi++) {
 540         char *arg = (*argv)[argi];
 541         isVMType = 0;
 542 
 543         if (IsJavaArgs()) {
 544             if (arg[0] != '-') {
 545                 newArgv[newArgvIdx++] = arg;
 546                 continue;
 547             }
 548         } else {
 549             if (JLI_StrCmp(arg, "-classpath") == 0 ||
 550                 JLI_StrCmp(arg, "-cp") == 0 ||
 551                 JLI_StrCmp(arg, "-modulepath") == 0 ||
 552                 JLI_StrCmp(arg, "-mp") == 0 ||
 553                 JLI_StrCmp(arg, "-upgrademodulepath") == 0 ||
 554                 JLI_StrCmp(arg, "-addmods") == 0 ||
 555                 JLI_StrCmp(arg, "-limitmods") == 0) {
 556                 newArgv[newArgvIdx++] = arg;
 557                 argi++;
 558                 if (argi < argc) {
 559                     newArgv[newArgvIdx++] = (*argv)[argi];
 560                 }
 561                 continue;
 562             }
 563             if (arg[0] != '-') break;
 564         }
 565 
 566         /* Did the user pass an explicit VM type? */
 567         i = KnownVMIndex(arg);
 568         if (i >= 0) {
 569             jvmtype = knownVMs[jvmidx = i].name + 1; /* skip the - */
 570             isVMType = 1;
 571             *pargc = *pargc - 1;
 572         }
 573 
 574         /* Did the user specify an "alternate" VM? */
 575         else if (JLI_StrCCmp(arg, "-XXaltjvm=") == 0 || JLI_StrCCmp(arg, "-J-XXaltjvm=") == 0) {
 576             isVMType = 1;
 577             jvmtype = arg+((arg[1]=='X')? 10 : 12);
 578             jvmidx = -1;
 579         }
 580 
 581         if (!isVMType) {
 582             newArgv[newArgvIdx++] = arg;
 583         }
 584     }
 585 
 586     /*
 587      * Finish copying the arguments if we aborted the above loop.
 588      * NOTE that if we aborted via "break" then we did NOT copy the
 589      * last argument above, and in addition argi will be less than
 590      * argc.
 591      */
 592     while (argi < argc) {
 593         newArgv[newArgvIdx++] = (*argv)[argi];
 594         argi++;
 595     }
 596 
 597     /* argv is null-terminated */
 598     newArgv[newArgvIdx] = 0;
 599 
 600     /* Copy back argv */
 601     *argv = newArgv;
 602     *pargc = newArgvIdx;
 603 
 604     /* use the default VM type if not specified (no alias processing) */
 605     if (jvmtype == NULL) {
 606       char* result = knownVMs[0].name+1;
 607       /* Use a different VM type if we are on a server class machine? */
 608       if ((knownVMs[0].flag == VM_IF_SERVER_CLASS) &&
 609           (ServerClassMachine() == JNI_TRUE)) {
 610         result = knownVMs[0].server_class+1;
 611       }
 612       JLI_TraceLauncher("Default VM: %s\n", result);
 613       return result;
 614     }
 615 
 616     /* if using an alternate VM, no alias processing */
 617     if (jvmidx < 0)
 618       return jvmtype;
 619 
 620     /* Resolve aliases first */
 621     {
 622       int loopCount = 0;
 623       while (knownVMs[jvmidx].flag == VM_ALIASED_TO) {
 624         int nextIdx = KnownVMIndex(knownVMs[jvmidx].alias);
 625 
 626         if (loopCount > knownVMsCount) {
 627           if (!speculative) {
 628             JLI_ReportErrorMessage(CFG_ERROR1);
 629             exit(1);
 630           } else {
 631             return "ERROR";
 632             /* break; */
 633           }
 634         }
 635 
 636         if (nextIdx < 0) {
 637           if (!speculative) {
 638             JLI_ReportErrorMessage(CFG_ERROR2, knownVMs[jvmidx].alias);
 639             exit(1);
 640           } else {
 641             return "ERROR";
 642           }
 643         }
 644         jvmidx = nextIdx;
 645         jvmtype = knownVMs[jvmidx].name+1;
 646         loopCount++;
 647       }
 648     }
 649 
 650     switch (knownVMs[jvmidx].flag) {
 651     case VM_WARN:
 652         if (!speculative) {
 653             JLI_ReportErrorMessage(CFG_WARN1, jvmtype, knownVMs[0].name + 1);
 654         }
 655         /* fall through */
 656     case VM_IGNORE:
 657         jvmtype = knownVMs[jvmidx=0].name + 1;
 658         /* fall through */
 659     case VM_KNOWN:
 660         break;
 661     case VM_ERROR:
 662         if (!speculative) {
 663             JLI_ReportErrorMessage(CFG_ERROR3, jvmtype);
 664             exit(1);
 665         } else {
 666             return "ERROR";
 667         }
 668     }
 669 
 670     return jvmtype;
 671 }
 672 
 673 /*
 674  * static void SetJvmEnvironment(int argc, char **argv);
 675  *   Is called just before the JVM is loaded.  We can set env variables
 676  *   that are consumed by the JVM.  This function is non-destructive,
 677  *   leaving the arg list intact.  The first use is for the JVM flag
 678  *   -XX:NativeMemoryTracking=value.
 679  */
 680 static void
 681 SetJvmEnvironment(int argc, char **argv) {
 682 
 683     static const char*  NMT_Env_Name    = "NMT_LEVEL_";
 684     int i;
 685     for (i = 0; i < argc; i++) {
 686         char *arg = argv[i];
 687         /*
 688          * Since this must be a VM flag we stop processing once we see
 689          * an argument the launcher would not have processed beyond (such
 690          * as -version or -h), or an argument that indicates the following
 691          * arguments are for the application (i.e. the main class name, or
 692          * the -jar argument).
 693          */
 694         if (i > 0) {
 695             char *prev = argv[i - 1];
 696             // skip non-dash arg preceded by class path specifiers
 697             if (*arg != '-' &&
 698                     ((JLI_StrCmp(prev, "-cp") == 0
 699                     || JLI_StrCmp(prev, "-classpath") == 0))) {
 700                 continue;
 701             }
 702 
 703             if (*arg != '-'
 704                     || JLI_StrCmp(arg, "-version") == 0
 705                     || JLI_StrCmp(arg, "-fullversion") == 0
 706                     || JLI_StrCmp(arg, "-help") == 0
 707                     || JLI_StrCmp(arg, "-?") == 0
 708                     || JLI_StrCmp(arg, "-jar") == 0
 709                     || JLI_StrCmp(arg, "-X") == 0) {
 710                 return;
 711             }
 712         }
 713         /*
 714          * The following case checks for "-XX:NativeMemoryTracking=value".
 715          * If value is non null, an environmental variable set to this value
 716          * will be created to be used by the JVM.
 717          * The argument is passed to the JVM, which will check validity.
 718          * The JVM is responsible for removing the env variable.
 719          */
 720         if (JLI_StrCCmp(arg, "-XX:NativeMemoryTracking=") == 0) {
 721             int retval;
 722             // get what follows this parameter, include "="
 723             size_t pnlen = JLI_StrLen("-XX:NativeMemoryTracking=");
 724             if (JLI_StrLen(arg) > pnlen) {
 725                 char* value = arg + pnlen;
 726                 size_t pbuflen = pnlen + JLI_StrLen(value) + 10; // 10 max pid digits
 727 
 728                 /*
 729                  * ensures that malloc successful
 730                  * DONT JLI_MemFree() pbuf.  JLI_PutEnv() uses system call
 731                  *   that could store the address.
 732                  */
 733                 char * pbuf = (char*)JLI_MemAlloc(pbuflen);
 734 
 735                 JLI_Snprintf(pbuf, pbuflen, "%s%d=%s", NMT_Env_Name, JLI_GetPid(), value);
 736                 retval = JLI_PutEnv(pbuf);
 737                 if (JLI_IsTraceLauncher()) {
 738                     char* envName;
 739                     char* envBuf;
 740 
 741                     // ensures that malloc successful
 742                     envName = (char*)JLI_MemAlloc(pbuflen);
 743                     JLI_Snprintf(envName, pbuflen, "%s%d", NMT_Env_Name, JLI_GetPid());
 744 
 745                     printf("TRACER_MARKER: NativeMemoryTracking: env var is %s\n",envName);
 746                     printf("TRACER_MARKER: NativeMemoryTracking: putenv arg %s\n",pbuf);
 747                     envBuf = getenv(envName);
 748                     printf("TRACER_MARKER: NativeMemoryTracking: got value %s\n",envBuf);
 749                     free(envName);
 750                 }
 751 
 752             }
 753 
 754         }
 755 
 756     }
 757 }
 758 
 759 /* copied from HotSpot function "atomll()" */
 760 static int
 761 parse_size(const char *s, jlong *result) {
 762   jlong n = 0;
 763   int args_read = sscanf(s, JLONG_FORMAT_SPECIFIER, &n);
 764   if (args_read != 1) {
 765     return 0;
 766   }
 767   while (*s != '\0' && *s >= '0' && *s <= '9') {
 768     s++;
 769   }
 770   // 4705540: illegal if more characters are found after the first non-digit
 771   if (JLI_StrLen(s) > 1) {
 772     return 0;
 773   }
 774   switch (*s) {
 775     case 'T': case 't':
 776       *result = n * GB * KB;
 777       return 1;
 778     case 'G': case 'g':
 779       *result = n * GB;
 780       return 1;
 781     case 'M': case 'm':
 782       *result = n * MB;
 783       return 1;
 784     case 'K': case 'k':
 785       *result = n * KB;
 786       return 1;
 787     case '\0':
 788       *result = n;
 789       return 1;
 790     default:
 791       /* Create JVM with default stack and let VM handle malformed -Xss string*/
 792       return 0;
 793   }
 794 }
 795 
 796 /*
 797  * Adds a new VM option with the given name and value.
 798  */
 799 void
 800 AddOption(char *str, void *info)
 801 {
 802     /*
 803      * Expand options array if needed to accommodate at least one more
 804      * VM option.
 805      */
 806     if (numOptions >= maxOptions) {
 807         if (options == 0) {
 808             maxOptions = 4;
 809             options = JLI_MemAlloc(maxOptions * sizeof(JavaVMOption));
 810         } else {
 811             JavaVMOption *tmp;
 812             maxOptions *= 2;
 813             tmp = JLI_MemAlloc(maxOptions * sizeof(JavaVMOption));
 814             memcpy(tmp, options, numOptions * sizeof(JavaVMOption));
 815             JLI_MemFree(options);
 816             options = tmp;
 817         }
 818     }
 819     options[numOptions].optionString = str;
 820     options[numOptions++].extraInfo = info;
 821 
 822     if (JLI_StrCCmp(str, "-Xss") == 0) {
 823         jlong tmp;
 824         if (parse_size(str + 4, &tmp)) {
 825             threadStackSize = tmp;
 826             /*
 827              * Make sure the thread stack size is big enough that we won't get a stack
 828              * overflow before the JVM startup code can check to make sure the stack
 829              * is big enough.
 830              */
 831             if (threadStackSize < (jlong)STACK_SIZE_MINIMUM) {
 832                 threadStackSize = STACK_SIZE_MINIMUM;
 833             }
 834         }
 835     }
 836 
 837     if (JLI_StrCCmp(str, "-Xmx") == 0) {
 838         jlong tmp;
 839         if (parse_size(str + 4, &tmp)) {
 840             maxHeapSize = tmp;
 841         }
 842     }
 843 
 844     if (JLI_StrCCmp(str, "-Xms") == 0) {
 845         jlong tmp;
 846         if (parse_size(str + 4, &tmp)) {
 847            initialHeapSize = tmp;
 848         }
 849     }
 850 }
 851 
 852 static void
 853 SetClassPath(const char *s)
 854 {
 855     char *def;
 856     const char *orig = s;
 857     static const char format[] = "-Djava.class.path=%s";
 858     /*
 859      * usually we should not get a null pointer, but there are cases where
 860      * we might just get one, in which case we simply ignore it, and let the
 861      * caller deal with it
 862      */
 863     if (s == NULL)
 864         return;
 865     s = JLI_WildcardExpandClasspath(s);
 866     if (sizeof(format) - 2 + JLI_StrLen(s) < JLI_StrLen(s))
 867         // s is became corrupted after expanding wildcards
 868         return;
 869     def = JLI_MemAlloc(sizeof(format)
 870                        - 2 /* strlen("%s") */
 871                        + JLI_StrLen(s));
 872     sprintf(def, format, s);
 873     AddOption(def, NULL);
 874     if (s != orig)
 875         JLI_MemFree((char *) s);
 876     _have_classpath = JNI_TRUE;
 877 }
 878 
 879 static void
 880 SetModulePath(const char *s)
 881 {
 882     char *def;
 883     const char *orig = s;
 884     static const char format[] = "-Djdk.module.path=%s";
 885     if (s == NULL)
 886         return;
 887     s = JLI_WildcardExpandClasspath(s);
 888     def = JLI_MemAlloc(sizeof(format)
 889                        - 2 /* strlen("%s") */
 890                        + JLI_StrLen(s));
 891     sprintf(def, format, s);
 892     AddOption(def, NULL);
 893     if (s != orig)
 894         JLI_MemFree((char *) s);
 895 }
 896 
 897 static void
 898 SetUpgradeModulePath(const char *s)
 899 {
 900     char *def;
 901     const char *orig = s;
 902     static const char format[] = "-Djdk.upgrade.module.path=%s";
 903     if (s == NULL)
 904         return;
 905     s = JLI_WildcardExpandClasspath(s);
 906     def = JLI_MemAlloc(sizeof(format)
 907                        - 2 /* strlen("%s") */
 908                        + JLI_StrLen(s));
 909     sprintf(def, format, s);
 910     AddOption(def, NULL);
 911     if (s != orig)
 912         JLI_MemFree((char *) s);
 913 }
 914 
 915 static void
 916 SetMainModule(const char *s)
 917 {
 918     static const char format[] = "-Djdk.module.main=%s";
 919     char* slash = JLI_StrChr(s, '/');
 920     size_t s_len, def_len;
 921     char *def;
 922 
 923     /* value may be <module> or <module>/<mainclass> */
 924     if (slash == NULL) {
 925         s_len = JLI_StrLen(s);
 926     } else {
 927         s_len = (size_t) (slash - s);
 928     }
 929     def_len = sizeof(format)
 930                - 2 /* strlen("%s") */
 931                + s_len;
 932     def = JLI_MemAlloc(def_len);
 933     JLI_Snprintf(def, def_len, format, s);
 934     AddOption(def, NULL);
 935 }
 936 
 937 static void
 938 SetAddModulesProp(const char *mods) {
 939     size_t buflen = JLI_StrLen(mods) + 40;
 940     char *prop = (char *)JLI_MemAlloc(buflen);
 941     JLI_Snprintf(prop, buflen, "-Djdk.launcher.addmods=%s", mods);
 942     AddOption(prop, NULL);
 943 }
 944 
 945 static void
 946 SetLimitModulesProp(const char *mods) {
 947     size_t buflen = JLI_StrLen(mods) + 40;
 948     char *prop = (char *)JLI_MemAlloc(buflen);
 949     JLI_Snprintf(prop, buflen, "-Djdk.launcher.limitmods=%s", mods);
 950     AddOption(prop, NULL);
 951 }
 952 
 953 static void
 954 SetAddReadsProp(const jint n, const char *s) {
 955     size_t buflen = JLI_StrLen(s) + 40;
 956     char *prop = (char *)JLI_MemAlloc(buflen);
 957     JLI_Snprintf(prop, buflen, "-Djdk.launcher.addreads.%d=%s", n, s);
 958     AddOption(prop, NULL);
 959 }
 960 
 961 static void
 962 SetAddExportsProp(const jint n, const char *s) {
 963     size_t buflen = JLI_StrLen(s) + 40;
 964     char *prop = (char *)JLI_MemAlloc(buflen);
 965     JLI_Snprintf(prop, buflen, "-Djdk.launcher.addexports.%d=%s", n, s);
 966     AddOption(prop, NULL);
 967 }
 968 
 969 static void
 970 SetPatchProp(const jint n, const char *s) {
 971     size_t buflen = JLI_StrLen(s) + 40;
 972     char *prop = (char *)JLI_MemAlloc(buflen);
 973     JLI_Snprintf(prop, buflen, "-Djdk.launcher.patch.%d=%s", n, s);
 974     AddOption(prop, NULL);
 975 }
 976 
 977 /*
 978  * The SelectVersion() routine ensures that an appropriate version of
 979  * the JRE is running.  The specification for the appropriate version
 980  * is obtained from either the manifest of a jar file (preferred) or
 981  * from command line options.
 982  * The routine also parses splash screen command line options and
 983  * passes on their values in private environment variables.
 984  */
 985 static void
 986 SelectVersion(int argc, char **argv, char **main_class)
 987 {
 988     char    *arg;
 989     char    *operand;
 990     char    *version = NULL;
 991     char    *jre = NULL;
 992     int     jarflag = 0;
 993     int     headlessflag = 0;
 994     int     restrict_search = -1;               /* -1 implies not known */
 995     manifest_info info;
 996     char    env_entry[MAXNAMELEN + 24] = ENV_ENTRY "=";
 997     char    *splash_file_name = NULL;
 998     char    *splash_jar_name = NULL;
 999     char    *env_in;
1000     int     res;
1001 
1002     /*
1003      * If the version has already been selected, set *main_class
1004      * with the value passed through the environment (if any) and
1005      * simply return.
1006      */
1007 
1008     /*
1009      * This environmental variable can be set by mJRE capable JREs
1010      * [ 1.5 thru 1.8 ].  All other aspects of mJRE processing have been
1011      * stripped by those JREs.  This environmental variable allows 1.9+
1012      * JREs to be started by these mJRE capable JREs.
1013      * Note that mJRE directives in the jar manifest file would have been
1014      * ignored for a JRE started by another JRE...
1015      * .. skipped for JRE 1.5 and beyond.
1016      * .. not even checked for pre 1.5.
1017      */
1018     if ((env_in = getenv(ENV_ENTRY)) != NULL) {
1019         if (*env_in != '\0')
1020             *main_class = JLI_StringDup(env_in);
1021         return;
1022     }
1023 
1024     /*
1025      * Scan through the arguments for options relevant to multiple JRE
1026      * support.  Multiple JRE support existed in JRE versions 1.5 thru 1.8.
1027      *
1028      * This capability is no longer available with JRE versions 1.9 and later.
1029      * These command line options are reported as errors.
1030      */
1031     argc--;
1032     argv++;
1033     while ((arg = *argv) != 0 && *arg == '-') {
1034         if (JLI_StrCCmp(arg, "-version:") == 0) {
1035             JLI_ReportErrorMessage(SPC_ERROR1);
1036         } else if (JLI_StrCmp(arg, "-jre-restrict-search") == 0) {
1037             JLI_ReportErrorMessage(SPC_ERROR2);
1038         } else if (JLI_StrCmp(arg, "-jre-no-restrict-search") == 0) {
1039             JLI_ReportErrorMessage(SPC_ERROR2);
1040         } else {
1041             if (JLI_StrCmp(arg, "-jar") == 0)
1042                 jarflag = 1;
1043             /* deal with "unfortunate" classpath syntax */
1044             if ((JLI_StrCmp(arg, "-classpath") == 0 || JLI_StrCmp(arg, "-cp") == 0) &&
1045               (argc >= 2)) {
1046                 argc--;
1047                 argv++;
1048                 arg = *argv;
1049             }
1050 
1051             /*
1052              * Checking for headless toolkit option in the some way as AWT does:
1053              * "true" means true and any other value means false
1054              */
1055             if (JLI_StrCmp(arg, "-Djava.awt.headless=true") == 0) {
1056                 headlessflag = 1;
1057             } else if (JLI_StrCCmp(arg, "-Djava.awt.headless=") == 0) {
1058                 headlessflag = 0;
1059             } else if (JLI_StrCCmp(arg, "-splash:") == 0) {
1060                 splash_file_name = arg+8;
1061             }
1062         }
1063         argc--;
1064         argv++;
1065     }
1066     if (argc <= 0) {    /* No operand? Possibly legit with -[full]version */
1067         operand = NULL;
1068     } else {
1069         argc--;
1070         operand = *argv++;
1071     }
1072 
1073     /*
1074      * If there is a jar file, read the manifest. If the jarfile can't be
1075      * read, the manifest can't be read from the jar file, or the manifest
1076      * is corrupt, issue the appropriate error messages and exit.
1077      *
1078      * Even if there isn't a jar file, construct a manifest_info structure
1079      * containing the command line information.  It's a convenient way to carry
1080      * this data around.
1081      */
1082     if (jarflag && operand) {
1083         if ((res = JLI_ParseManifest(operand, &info)) != 0) {
1084             if (res == -1)
1085                 JLI_ReportErrorMessage(JAR_ERROR2, operand);
1086             else
1087                 JLI_ReportErrorMessage(JAR_ERROR3, operand);
1088             exit(1);
1089         }
1090 
1091         /*
1092          * Command line splash screen option should have precedence
1093          * over the manifest, so the manifest data is used only if
1094          * splash_file_name has not been initialized above during command
1095          * line parsing
1096          */
1097         if (!headlessflag && !splash_file_name && info.splashscreen_image_file_name) {
1098             splash_file_name = info.splashscreen_image_file_name;
1099             splash_jar_name = operand;
1100         }
1101     } else {
1102         info.manifest_version = NULL;
1103         info.main_class = NULL;
1104         info.jre_version = NULL;
1105         info.jre_restrict_search = 0;
1106     }
1107 
1108     /*
1109      * Passing on splash screen info in environment variables
1110      */
1111     if (splash_file_name && !headlessflag) {
1112         char* splash_file_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_FILE_ENV_ENTRY "=")+JLI_StrLen(splash_file_name)+1);
1113         JLI_StrCpy(splash_file_entry, SPLASH_FILE_ENV_ENTRY "=");
1114         JLI_StrCat(splash_file_entry, splash_file_name);
1115         putenv(splash_file_entry);
1116     }
1117     if (splash_jar_name && !headlessflag) {
1118         char* splash_jar_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_JAR_ENV_ENTRY "=")+JLI_StrLen(splash_jar_name)+1);
1119         JLI_StrCpy(splash_jar_entry, SPLASH_JAR_ENV_ENTRY "=");
1120         JLI_StrCat(splash_jar_entry, splash_jar_name);
1121         putenv(splash_jar_entry);
1122     }
1123 
1124 
1125     /*
1126      * "Valid" returns (other than unrecoverable errors) follow.  Set
1127      * main_class as a side-effect of this routine.
1128      */
1129     if (info.main_class != NULL)
1130         *main_class = JLI_StringDup(info.main_class);
1131 
1132     if (info.jre_version == NULL) {
1133         JLI_FreeManifest();
1134         return;
1135     }
1136 
1137 }
1138 
1139 /*
1140  * Parses command line arguments.  Returns JNI_FALSE if launcher
1141  * should exit without starting vm, returns JNI_TRUE if vm needs
1142  * to be started to process given options.  *pret (the launcher
1143  * process return value) is set to 0 for a normal exit.
1144  */
1145 static jboolean
1146 ParseArguments(int *pargc, char ***pargv,
1147                int *pmode, char **pwhat,
1148                int *pret, const char *jrepath)
1149 {
1150     int argc = *pargc;
1151     char **argv = *pargv;
1152     int mode = LM_UNKNOWN;
1153     char *arg;
1154 
1155     *pret = 0;
1156 
1157     while ((arg = *argv) != 0 && *arg == '-') {
1158         argv++; --argc;
1159         if (JLI_StrCmp(arg, "-classpath") == 0 || JLI_StrCmp(arg, "-cp") == 0) {
1160             ARG_CHECK (argc, ARG_ERROR1, arg);
1161             SetClassPath(*argv);
1162             mode = LM_CLASS;
1163             argv++; --argc;
1164         } else if (JLI_StrCmp(arg, "-modulepath") == 0 || JLI_StrCmp(arg, "-mp") == 0) {
1165             ARG_CHECK (argc, ARG_ERROR4, arg);
1166             SetModulePath(*argv);
1167             argv++; --argc;
1168         } else if (JLI_StrCmp(arg, "-upgrademodulepath") == 0) {
1169             ARG_CHECK (argc, ARG_ERROR4, arg);
1170             SetUpgradeModulePath(*argv);
1171             argv++; --argc;
1172         } else if (JLI_StrCmp(arg, "-jar") == 0) {
1173             ARG_CHECK (argc, ARG_ERROR2, arg);
1174             mode = LM_JAR;
1175         } else if (JLI_StrCmp(arg, "-m") == 0) {
1176             ARG_CHECK (argc, ARG_ERROR5, arg);
1177             SetMainModule(*argv);
1178             mode = LM_MODULE;
1179         } else if (JLI_StrCmp(arg, "-addmods") == 0) {
1180             ARG_CHECK (argc, ARG_ERROR6, arg);
1181             SetAddModulesProp(*argv);
1182             argv++; --argc;
1183         } else if (JLI_StrCmp(arg, "-limitmods") == 0) {
1184             ARG_CHECK (argc, ARG_ERROR6, arg);
1185             SetLimitModulesProp(*argv);
1186             argv++; --argc;
1187         } else if (JLI_StrCmp(arg, "-listmods") == 0 ||
1188                    JLI_StrCCmp(arg, "-listmods:") == 0) {
1189             listModules = arg;
1190             return JNI_TRUE;
1191         } else if (JLI_StrCCmp(arg, "-XaddReads:") == 0) {
1192             static jint n;
1193             char *value = arg + 11;
1194             SetAddReadsProp(n++, value);
1195         } else if (JLI_StrCCmp(arg, "-XaddExports:") == 0) {
1196             static jint n;
1197             char *value = arg + 13;
1198             SetAddExportsProp(n++, value);
1199         } else if (JLI_StrCCmp(arg, "-Xpatch:") == 0) {
1200             static jint n;
1201             char *value = arg + 8;
1202             SetPatchProp(n++, value);
1203         } else if (JLI_StrCmp(arg, "-help") == 0 ||
1204                    JLI_StrCmp(arg, "-h") == 0 ||
1205                    JLI_StrCmp(arg, "-?") == 0) {
1206             printUsage = JNI_TRUE;
1207             return JNI_TRUE;
1208         } else if (JLI_StrCmp(arg, "-version") == 0) {
1209             printVersion = JNI_TRUE;
1210             return JNI_TRUE;
1211         } else if (JLI_StrCmp(arg, "-showversion") == 0) {
1212             showVersion = JNI_TRUE;
1213         } else if (JLI_StrCmp(arg, "-X") == 0) {
1214             printXUsage = JNI_TRUE;
1215             return JNI_TRUE;
1216 /*
1217  * The following case checks for -XshowSettings OR -XshowSetting:SUBOPT.
1218  * In the latter case, any SUBOPT value not recognized will default to "all"
1219  */
1220         } else if (JLI_StrCmp(arg, "-XshowSettings") == 0 ||
1221                    JLI_StrCCmp(arg, "-XshowSettings:") == 0) {
1222             showSettings = arg;
1223         } else if (JLI_StrCmp(arg, "-Xdiag") == 0) {
1224             AddOption("-Dsun.java.launcher.diag=true", NULL);
1225             AddOption("-Djdk.launcher.traceResolver=true", NULL);
1226         } else if (JLI_StrCmp(arg, "-Xdiag:resolver") == 0) {
1227             AddOption("-Djdk.launcher.traceResolver=true", NULL);
1228 /*
1229  * The following case provide backward compatibility with old-style
1230  * command line options.
1231  */
1232         } else if (JLI_StrCmp(arg, "-fullversion") == 0) {
1233             JLI_ReportMessage("%s full version \"%s\"", _launcher_name, GetFullVersion());
1234             return JNI_FALSE;
1235         } else if (JLI_StrCmp(arg, "-verbosegc") == 0) {
1236             AddOption("-verbose:gc", NULL);
1237         } else if (JLI_StrCmp(arg, "-t") == 0) {
1238             AddOption("-Xt", NULL);
1239         } else if (JLI_StrCmp(arg, "-tm") == 0) {
1240             AddOption("-Xtm", NULL);
1241         } else if (JLI_StrCmp(arg, "-debug") == 0) {
1242             AddOption("-Xdebug", NULL);
1243         } else if (JLI_StrCmp(arg, "-noclassgc") == 0) {
1244             AddOption("-Xnoclassgc", NULL);
1245         } else if (JLI_StrCmp(arg, "-Xfuture") == 0) {
1246             AddOption("-Xverify:all", NULL);
1247         } else if (JLI_StrCmp(arg, "-verify") == 0) {
1248             AddOption("-Xverify:all", NULL);
1249         } else if (JLI_StrCmp(arg, "-verifyremote") == 0) {
1250             AddOption("-Xverify:remote", NULL);
1251         } else if (JLI_StrCmp(arg, "-noverify") == 0) {
1252             AddOption("-Xverify:none", NULL);
1253         } else if (JLI_StrCCmp(arg, "-ss") == 0 ||
1254                    JLI_StrCCmp(arg, "-oss") == 0 ||
1255                    JLI_StrCCmp(arg, "-ms") == 0 ||
1256                    JLI_StrCCmp(arg, "-mx") == 0) {
1257             char *tmp = JLI_MemAlloc(JLI_StrLen(arg) + 6);
1258             sprintf(tmp, "-X%s", arg + 1); /* skip '-' */
1259             AddOption(tmp, NULL);
1260         } else if (JLI_StrCmp(arg, "-checksource") == 0 ||
1261                    JLI_StrCmp(arg, "-cs") == 0 ||
1262                    JLI_StrCmp(arg, "-noasyncgc") == 0) {
1263             /* No longer supported */
1264             JLI_ReportErrorMessage(ARG_WARN, arg);
1265         } else if (JLI_StrCCmp(arg, "-splash:") == 0) {
1266             ; /* Ignore machine independent options already handled */
1267         } else if (ProcessPlatformOption(arg)) {
1268             ; /* Processing of platform dependent options */
1269         } else if (RemovableOption(arg)) {
1270             ; /* Do not pass option to vm. */
1271         } else {
1272             /* java.class.path set on the command line */
1273             if (JLI_StrCCmp(arg, "-Djava.class.path=") == 0) {
1274                 _have_classpath = JNI_TRUE;
1275             }
1276             AddOption(arg, NULL);
1277         }
1278     }
1279 
1280     if (--argc >= 0) {
1281         *pwhat = *argv++;
1282     }
1283 
1284     if (*pwhat == NULL) {
1285         *pret = 1;
1286     } else if (mode == LM_UNKNOWN) {
1287         /* default to LM_CLASS if -m, -jar and -cp options are
1288          * not specified */
1289         if (!_have_classpath) {
1290             SetClassPath(".");
1291         }
1292         mode = LM_CLASS;
1293     }
1294 
1295     if (argc >= 0) {
1296         *pargc = argc;
1297         *pargv = argv;
1298     }
1299 
1300     *pmode = mode;
1301 
1302     return JNI_TRUE;
1303 }
1304 
1305 /*
1306  * Initializes the Java Virtual Machine. Also frees options array when
1307  * finished.
1308  */
1309 static jboolean
1310 InitializeJVM(JavaVM **pvm, JNIEnv **penv, InvocationFunctions *ifn)
1311 {
1312     JavaVMInitArgs args;
1313     jint r;
1314 
1315     memset(&args, 0, sizeof(args));
1316     args.version  = JNI_VERSION_1_2;
1317     args.nOptions = numOptions;
1318     args.options  = options;
1319     args.ignoreUnrecognized = JNI_FALSE;
1320 
1321     if (JLI_IsTraceLauncher()) {
1322         int i = 0;
1323         printf("JavaVM args:\n    ");
1324         printf("version 0x%08lx, ", (long)args.version);
1325         printf("ignoreUnrecognized is %s, ",
1326                args.ignoreUnrecognized ? "JNI_TRUE" : "JNI_FALSE");
1327         printf("nOptions is %ld\n", (long)args.nOptions);
1328         for (i = 0; i < numOptions; i++)
1329             printf("    option[%2d] = '%s'\n",
1330                    i, args.options[i].optionString);
1331     }
1332 
1333     r = ifn->CreateJavaVM(pvm, (void **)penv, &args);
1334     JLI_MemFree(options);
1335     return r == JNI_OK;
1336 }
1337 
1338 static jclass helperClass = NULL;
1339 
1340 jclass
1341 GetLauncherHelperClass(JNIEnv *env)
1342 {
1343     if (helperClass == NULL) {
1344         NULL_CHECK0(helperClass = FindBootStrapClass(env,
1345                 "sun/launcher/LauncherHelper"));
1346     }
1347     return helperClass;
1348 }
1349 
1350 static jmethodID makePlatformStringMID = NULL;
1351 /*
1352  * Returns a new Java string object for the specified platform string.
1353  */
1354 static jstring
1355 NewPlatformString(JNIEnv *env, char *s)
1356 {
1357     int len = (int)JLI_StrLen(s);
1358     jbyteArray ary;
1359     jclass cls = GetLauncherHelperClass(env);
1360     NULL_CHECK0(cls);
1361     if (s == NULL)
1362         return 0;
1363 
1364     ary = (*env)->NewByteArray(env, len);
1365     if (ary != 0) {
1366         jstring str = 0;
1367         (*env)->SetByteArrayRegion(env, ary, 0, len, (jbyte *)s);
1368         if (!(*env)->ExceptionOccurred(env)) {
1369             if (makePlatformStringMID == NULL) {
1370                 NULL_CHECK0(makePlatformStringMID = (*env)->GetStaticMethodID(env,
1371                         cls, "makePlatformString", "(Z[B)Ljava/lang/String;"));
1372             }
1373             str = (*env)->CallStaticObjectMethod(env, cls,
1374                     makePlatformStringMID, USE_STDERR, ary);
1375             (*env)->DeleteLocalRef(env, ary);
1376             return str;
1377         }
1378     }
1379     return 0;
1380 }
1381 
1382 /*
1383  * Returns a new array of Java string objects for the specified
1384  * array of platform strings.
1385  */
1386 jobjectArray
1387 NewPlatformStringArray(JNIEnv *env, char **strv, int strc)
1388 {
1389     jarray cls;
1390     jarray ary;
1391     int i;
1392 
1393     NULL_CHECK0(cls = FindBootStrapClass(env, "java/lang/String"));
1394     NULL_CHECK0(ary = (*env)->NewObjectArray(env, strc, cls, 0));
1395     for (i = 0; i < strc; i++) {
1396         jstring str = NewPlatformString(env, *strv++);
1397         NULL_CHECK0(str);
1398         (*env)->SetObjectArrayElement(env, ary, i, str);
1399         (*env)->DeleteLocalRef(env, str);
1400     }
1401     return ary;
1402 }
1403 
1404 /*
1405  * Loads a class and verifies that the main class is present and it is ok to
1406  * call it for more details refer to the java implementation.
1407  */
1408 static jclass
1409 LoadMainClass(JNIEnv *env, int mode, char *name)
1410 {
1411     jmethodID mid;
1412     jstring str;
1413     jobject result;
1414     jlong start, end;
1415     jclass cls = GetLauncherHelperClass(env);
1416     NULL_CHECK0(cls);
1417     if (JLI_IsTraceLauncher()) {
1418         start = CounterGet();
1419     }
1420     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1421                 "checkAndLoadMain",
1422                 "(ZILjava/lang/String;)Ljava/lang/Class;"));
1423 
1424     NULL_CHECK0(str = NewPlatformString(env, name));
1425     NULL_CHECK0(result = (*env)->CallStaticObjectMethod(env, cls, mid,
1426                                                         USE_STDERR, mode, str));
1427 
1428     if (JLI_IsTraceLauncher()) {
1429         end   = CounterGet();
1430         printf("%ld micro seconds to load main class\n",
1431                (long)(jint)Counter2Micros(end-start));
1432         printf("----%s----\n", JLDEBUG_ENV_ENTRY);
1433     }
1434 
1435     return (jclass)result;
1436 }
1437 
1438 static jclass
1439 GetApplicationClass(JNIEnv *env)
1440 {
1441     jmethodID mid;
1442     jclass cls = GetLauncherHelperClass(env);
1443     NULL_CHECK0(cls);
1444     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1445                 "getApplicationClass",
1446                 "()Ljava/lang/Class;"));
1447 
1448     return (*env)->CallStaticObjectMethod(env, cls, mid);
1449 }
1450 
1451 /*
1452  * For tools, convert command line args thus:
1453  *   javac -cp foo:foo/"*" -J-ms32m ...
1454  *   java -ms32m -cp JLI_WildcardExpandClasspath(foo:foo/"*") ...
1455  *
1456  * Takes 4 parameters, and returns the populated arguments
1457  */
1458 static void
1459 TranslateApplicationArgs(int jargc, const char **jargv, int *pargc, char ***pargv)
1460 {
1461     int argc = *pargc;
1462     char **argv = *pargv;
1463     int nargc = argc + jargc;
1464     char **nargv = JLI_MemAlloc((nargc + 1) * sizeof(char *));
1465     int i;
1466 
1467     *pargc = nargc;
1468     *pargv = nargv;
1469 
1470     /* Copy the VM arguments (i.e. prefixed with -J) */
1471     for (i = 0; i < jargc; i++) {
1472         const char *arg = jargv[i];
1473         if (arg[0] == '-' && arg[1] == 'J') {
1474             *nargv++ = ((arg + 2) == NULL) ? NULL : JLI_StringDup(arg + 2);
1475         }
1476     }
1477 
1478     for (i = 0; i < argc; i++) {
1479         char *arg = argv[i];
1480         if (arg[0] == '-' && arg[1] == 'J') {
1481             if (arg[2] == '\0') {
1482                 JLI_ReportErrorMessage(ARG_ERROR3);
1483                 exit(1);
1484             }
1485             *nargv++ = arg + 2;
1486         }
1487     }
1488 
1489     /* Copy the rest of the arguments */
1490     for (i = 0; i < jargc ; i++) {
1491         const char *arg = jargv[i];
1492         if (arg[0] != '-' || arg[1] != 'J') {
1493             *nargv++ = (arg == NULL) ? NULL : JLI_StringDup(arg);
1494         }
1495     }
1496     for (i = 0; i < argc; i++) {
1497         char *arg = argv[i];
1498         if (arg[0] == '-') {
1499             if (arg[1] == 'J')
1500                 continue;
1501             if (IsWildCardEnabled() && arg[1] == 'c'
1502                 && (JLI_StrCmp(arg, "-cp") == 0 ||
1503                     JLI_StrCmp(arg, "-classpath") == 0)
1504                 && i < argc - 1) {
1505                 *nargv++ = arg;
1506                 *nargv++ = (char *) JLI_WildcardExpandClasspath(argv[i+1]);
1507                 i++;
1508                 continue;
1509             }
1510         }
1511         *nargv++ = arg;
1512     }
1513     *nargv = 0;
1514 }
1515 
1516 /*
1517  * For our tools, we try to add 3 VM options:
1518  *      -Denv.class.path=<envcp>
1519  *      -Dapplication.home=<apphome>
1520  *      -Djava.class.path=<appcp>
1521  * <envcp>   is the user's setting of CLASSPATH -- for instance the user
1522  *           tells javac where to find binary classes through this environment
1523  *           variable.  Notice that users will be able to compile against our
1524  *           tools classes (sun.tools.javac.Main) only if they explicitly add
1525  *           tools.jar to CLASSPATH.
1526  * <apphome> is the directory where the application is installed.
1527  * <appcp>   is the classpath to where our apps' classfiles are.
1528  */
1529 static jboolean
1530 AddApplicationOptions(int cpathc, const char **cpathv)
1531 {
1532     char *envcp, *appcp, *apphome;
1533     char home[MAXPATHLEN]; /* application home */
1534     char separator[] = { PATH_SEPARATOR, '\0' };
1535     int size, i;
1536 
1537     {
1538         const char *s = getenv("CLASSPATH");
1539         if (s) {
1540             s = (char *) JLI_WildcardExpandClasspath(s);
1541             /* 40 for -Denv.class.path= */
1542             if (JLI_StrLen(s) + 40 > JLI_StrLen(s)) { // Safeguard from overflow
1543                 envcp = (char *)JLI_MemAlloc(JLI_StrLen(s) + 40);
1544                 sprintf(envcp, "-Denv.class.path=%s", s);
1545                 AddOption(envcp, NULL);
1546             }
1547         }
1548     }
1549 
1550     if (!GetApplicationHome(home, sizeof(home))) {
1551         JLI_ReportErrorMessage(CFG_ERROR5);
1552         return JNI_FALSE;
1553     }
1554 
1555     /* 40 for '-Dapplication.home=' */
1556     apphome = (char *)JLI_MemAlloc(JLI_StrLen(home) + 40);
1557     sprintf(apphome, "-Dapplication.home=%s", home);
1558     AddOption(apphome, NULL);
1559 
1560     /* How big is the application's classpath? */
1561     size = 40;                                 /* 40: "-Djava.class.path=" */
1562     for (i = 0; i < cpathc; i++) {
1563         size += (int)JLI_StrLen(home) + (int)JLI_StrLen(cpathv[i]) + 1; /* 1: separator */
1564     }
1565     appcp = (char *)JLI_MemAlloc(size + 1);
1566     JLI_StrCpy(appcp, "-Djava.class.path=");
1567     for (i = 0; i < cpathc; i++) {
1568         JLI_StrCat(appcp, home);                        /* c:\program files\myapp */
1569         JLI_StrCat(appcp, cpathv[i]);           /* \lib\myapp.jar         */
1570         JLI_StrCat(appcp, separator);           /* ;                      */
1571     }
1572     appcp[JLI_StrLen(appcp)-1] = '\0';  /* remove trailing path separator */
1573     AddOption(appcp, NULL);
1574     return JNI_TRUE;
1575 }
1576 
1577 /*
1578  * inject the -Dsun.java.command pseudo property into the args structure
1579  * this pseudo property is used in the HotSpot VM to expose the
1580  * Java class name and arguments to the main method to the VM. The
1581  * HotSpot VM uses this pseudo property to store the Java class name
1582  * (or jar file name) and the arguments to the class's main method
1583  * to the instrumentation memory region. The sun.java.command pseudo
1584  * property is not exported by HotSpot to the Java layer.
1585  */
1586 void
1587 SetJavaCommandLineProp(char *what, int argc, char **argv)
1588 {
1589 
1590     int i = 0;
1591     size_t len = 0;
1592     char* javaCommand = NULL;
1593     char* dashDstr = "-Dsun.java.command=";
1594 
1595     if (what == NULL) {
1596         /* unexpected, one of these should be set. just return without
1597          * setting the property
1598          */
1599         return;
1600     }
1601 
1602     /* determine the amount of memory to allocate assuming
1603      * the individual components will be space separated
1604      */
1605     len = JLI_StrLen(what);
1606     for (i = 0; i < argc; i++) {
1607         len += JLI_StrLen(argv[i]) + 1;
1608     }
1609 
1610     /* allocate the memory */
1611     javaCommand = (char*) JLI_MemAlloc(len + JLI_StrLen(dashDstr) + 1);
1612 
1613     /* build the -D string */
1614     *javaCommand = '\0';
1615     JLI_StrCat(javaCommand, dashDstr);
1616     JLI_StrCat(javaCommand, what);
1617 
1618     for (i = 0; i < argc; i++) {
1619         /* the components of the string are space separated. In
1620          * the case of embedded white space, the relationship of
1621          * the white space separated components to their true
1622          * positional arguments will be ambiguous. This issue may
1623          * be addressed in a future release.
1624          */
1625         JLI_StrCat(javaCommand, " ");
1626         JLI_StrCat(javaCommand, argv[i]);
1627     }
1628 
1629     AddOption(javaCommand, NULL);
1630 }
1631 
1632 /*
1633  * JVM would like to know if it's created by a standard Sun launcher, or by
1634  * user native application, the following property indicates the former.
1635  */
1636 void
1637 SetJavaLauncherProp() {
1638   AddOption("-Dsun.java.launcher=SUN_STANDARD", NULL);
1639 }
1640 
1641 /*
1642  * Prints the version information from the java.version and other properties.
1643  */
1644 static void
1645 PrintJavaVersion(JNIEnv *env, jboolean extraLF)
1646 {
1647     jclass ver;
1648     jmethodID print;
1649 
1650     NULL_CHECK(ver = FindBootStrapClass(env, "java/lang/VersionProps"));
1651     NULL_CHECK(print = (*env)->GetStaticMethodID(env,
1652                                                  ver,
1653                                                  (extraLF == JNI_TRUE) ? "println" : "print",
1654                                                  "()V"
1655                                                  )
1656               );
1657 
1658     (*env)->CallStaticVoidMethod(env, ver, print);
1659 }
1660 
1661 /*
1662  * Prints all the Java settings, see the java implementation for more details.
1663  */
1664 static void
1665 ShowSettings(JNIEnv *env, char *optString)
1666 {
1667     jmethodID showSettingsID;
1668     jstring joptString;
1669     jclass cls = GetLauncherHelperClass(env);
1670     NULL_CHECK(cls);
1671     NULL_CHECK(showSettingsID = (*env)->GetStaticMethodID(env, cls,
1672             "showSettings", "(ZLjava/lang/String;JJJZ)V"));
1673     NULL_CHECK(joptString = (*env)->NewStringUTF(env, optString));
1674     (*env)->CallStaticVoidMethod(env, cls, showSettingsID,
1675                                  USE_STDERR,
1676                                  joptString,
1677                                  (jlong)initialHeapSize,
1678                                  (jlong)maxHeapSize,
1679                                  (jlong)threadStackSize,
1680                                  ServerClassMachine());
1681 }
1682 
1683 /**
1684  * List modules supported by the runtime
1685  */
1686 static void
1687 ListModules(JNIEnv *env, char *optString)
1688 {
1689     jmethodID listModulesID;
1690     jstring joptString;
1691     jclass cls = GetLauncherHelperClass(env);
1692     NULL_CHECK(cls);
1693     NULL_CHECK(listModulesID = (*env)->GetStaticMethodID(env, cls,
1694             "listModules", "(ZLjava/lang/String;)V"));
1695     NULL_CHECK(joptString = (*env)->NewStringUTF(env, optString));
1696     (*env)->CallStaticVoidMethod(env, cls, listModulesID,
1697                                  USE_STDERR,
1698                                  joptString);
1699 }
1700 
1701 /**
1702  * Set native thread name if possible.
1703  */
1704 static void
1705 SetNativeThreadName(JNIEnv *env, char *name)
1706 {
1707     jmethodID currentThreadID, setNativeNameID;
1708     jobject currentThread;
1709     jstring nameString;
1710     jclass cls;
1711 
1712     NULL_CHECK(cls = FindBootStrapClass(env, "java/lang/Thread"));
1713     NULL_CHECK(currentThreadID = (*env)->GetStaticMethodID(env, cls,
1714                                      "currentThread", "()Ljava/lang/Thread;"));
1715     NULL_CHECK(currentThread = (*env)->CallStaticObjectMethod(env, cls,
1716                                                               currentThreadID));
1717     NULL_CHECK(setNativeNameID = (*env)->GetMethodID(env, cls,
1718                                     "setNativeName", "(Ljava/lang/String;Z)V"));
1719     NULL_CHECK(nameString = (*env)->NewStringUTF(env, name));
1720     (*env)->CallVoidMethod(env, currentThread, setNativeNameID,
1721                            nameString, JNI_TRUE);
1722 }
1723 
1724 /*
1725  * Prints default usage or the Xusage message, see sun.launcher.LauncherHelper.java
1726  */
1727 static void
1728 PrintUsage(JNIEnv* env, jboolean doXUsage)
1729 {
1730   jmethodID initHelp, vmSelect, vmSynonym, vmErgo, printHelp, printXUsageMessage;
1731   jstring jprogname, vm1, vm2;
1732   int i;
1733   jclass cls = GetLauncherHelperClass(env);
1734   NULL_CHECK(cls);
1735   if (doXUsage) {
1736     NULL_CHECK(printXUsageMessage = (*env)->GetStaticMethodID(env, cls,
1737                                         "printXUsageMessage", "(Z)V"));
1738     (*env)->CallStaticVoidMethod(env, cls, printXUsageMessage, USE_STDERR);
1739   } else {
1740     NULL_CHECK(initHelp = (*env)->GetStaticMethodID(env, cls,
1741                                         "initHelpMessage", "(Ljava/lang/String;)V"));
1742 
1743     NULL_CHECK(vmSelect = (*env)->GetStaticMethodID(env, cls, "appendVmSelectMessage",
1744                                         "(Ljava/lang/String;Ljava/lang/String;)V"));
1745 
1746     NULL_CHECK(vmSynonym = (*env)->GetStaticMethodID(env, cls,
1747                                         "appendVmSynonymMessage",
1748                                         "(Ljava/lang/String;Ljava/lang/String;)V"));
1749     NULL_CHECK(vmErgo = (*env)->GetStaticMethodID(env, cls,
1750                                         "appendVmErgoMessage", "(ZLjava/lang/String;)V"));
1751 
1752     NULL_CHECK(printHelp = (*env)->GetStaticMethodID(env, cls,
1753                                         "printHelpMessage", "(Z)V"));
1754 
1755     NULL_CHECK(jprogname = (*env)->NewStringUTF(env, _program_name));
1756 
1757     /* Initialize the usage message with the usual preamble */
1758     (*env)->CallStaticVoidMethod(env, cls, initHelp, jprogname);
1759     CHECK_EXCEPTION_RETURN();
1760 
1761 
1762     /* Assemble the other variant part of the usage */
1763     if ((knownVMs[0].flag == VM_KNOWN) ||
1764         (knownVMs[0].flag == VM_IF_SERVER_CLASS)) {
1765       NULL_CHECK(vm1 = (*env)->NewStringUTF(env, knownVMs[0].name));
1766       NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[0].name+1));
1767       (*env)->CallStaticVoidMethod(env, cls, vmSelect, vm1, vm2);
1768       CHECK_EXCEPTION_RETURN();
1769     }
1770     for (i=1; i<knownVMsCount; i++) {
1771       if (knownVMs[i].flag == VM_KNOWN) {
1772         NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
1773         NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].name+1));
1774         (*env)->CallStaticVoidMethod(env, cls, vmSelect, vm1, vm2);
1775         CHECK_EXCEPTION_RETURN();
1776       }
1777     }
1778     for (i=1; i<knownVMsCount; i++) {
1779       if (knownVMs[i].flag == VM_ALIASED_TO) {
1780         NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
1781         NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].alias+1));
1782         (*env)->CallStaticVoidMethod(env, cls, vmSynonym, vm1, vm2);
1783         CHECK_EXCEPTION_RETURN();
1784       }
1785     }
1786 
1787     /* The first known VM is the default */
1788     {
1789       jboolean isServerClassMachine = ServerClassMachine();
1790 
1791       const char* defaultVM  =  knownVMs[0].name+1;
1792       if ((knownVMs[0].flag == VM_IF_SERVER_CLASS) && isServerClassMachine) {
1793         defaultVM = knownVMs[0].server_class+1;
1794       }
1795 
1796       NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, defaultVM));
1797       (*env)->CallStaticVoidMethod(env, cls, vmErgo, isServerClassMachine,  vm1);
1798       CHECK_EXCEPTION_RETURN();
1799     }
1800 
1801     /* Complete the usage message and print to stderr*/
1802     (*env)->CallStaticVoidMethod(env, cls, printHelp, USE_STDERR);
1803   }
1804   return;
1805 }
1806 
1807 /*
1808  * Read the jvm.cfg file and fill the knownJVMs[] array.
1809  *
1810  * The functionality of the jvm.cfg file is subject to change without
1811  * notice and the mechanism will be removed in the future.
1812  *
1813  * The lexical structure of the jvm.cfg file is as follows:
1814  *
1815  *     jvmcfg         :=  { vmLine }
1816  *     vmLine         :=  knownLine
1817  *                    |   aliasLine
1818  *                    |   warnLine
1819  *                    |   ignoreLine
1820  *                    |   errorLine
1821  *                    |   predicateLine
1822  *                    |   commentLine
1823  *     knownLine      :=  flag  "KNOWN"                  EOL
1824  *     warnLine       :=  flag  "WARN"                   EOL
1825  *     ignoreLine     :=  flag  "IGNORE"                 EOL
1826  *     errorLine      :=  flag  "ERROR"                  EOL
1827  *     aliasLine      :=  flag  "ALIASED_TO"       flag  EOL
1828  *     predicateLine  :=  flag  "IF_SERVER_CLASS"  flag  EOL
1829  *     commentLine    :=  "#" text                       EOL
1830  *     flag           :=  "-" identifier
1831  *
1832  * The semantics are that when someone specifies a flag on the command line:
1833  * - if the flag appears on a knownLine, then the identifier is used as
1834  *   the name of the directory holding the JVM library (the name of the JVM).
1835  * - if the flag appears as the first flag on an aliasLine, the identifier
1836  *   of the second flag is used as the name of the JVM.
1837  * - if the flag appears on a warnLine, the identifier is used as the
1838  *   name of the JVM, but a warning is generated.
1839  * - if the flag appears on an ignoreLine, the identifier is recognized as the
1840  *   name of a JVM, but the identifier is ignored and the default vm used
1841  * - if the flag appears on an errorLine, an error is generated.
1842  * - if the flag appears as the first flag on a predicateLine, and
1843  *   the machine on which you are running passes the predicate indicated,
1844  *   then the identifier of the second flag is used as the name of the JVM,
1845  *   otherwise the identifier of the first flag is used as the name of the JVM.
1846  * If no flag is given on the command line, the first vmLine of the jvm.cfg
1847  * file determines the name of the JVM.
1848  * PredicateLines are only interpreted on first vmLine of a jvm.cfg file,
1849  * since they only make sense if someone hasn't specified the name of the
1850  * JVM on the command line.
1851  *
1852  * The intent of the jvm.cfg file is to allow several JVM libraries to
1853  * be installed in different subdirectories of a single JRE installation,
1854  * for space-savings and convenience in testing.
1855  * The intent is explicitly not to provide a full aliasing or predicate
1856  * mechanism.
1857  */
1858 jint
1859 ReadKnownVMs(const char *jvmCfgName, jboolean speculative)
1860 {
1861     FILE *jvmCfg;
1862     char line[MAXPATHLEN+20];
1863     int cnt = 0;
1864     int lineno = 0;
1865     jlong start, end;
1866     int vmType;
1867     char *tmpPtr;
1868     char *altVMName = NULL;
1869     char *serverClassVMName = NULL;
1870     static char *whiteSpace = " \t";
1871     if (JLI_IsTraceLauncher()) {
1872         start = CounterGet();
1873     }
1874 
1875     jvmCfg = fopen(jvmCfgName, "r");
1876     if (jvmCfg == NULL) {
1877       if (!speculative) {
1878         JLI_ReportErrorMessage(CFG_ERROR6, jvmCfgName);
1879         exit(1);
1880       } else {
1881         return -1;
1882       }
1883     }
1884     while (fgets(line, sizeof(line), jvmCfg) != NULL) {
1885         vmType = VM_UNKNOWN;
1886         lineno++;
1887         if (line[0] == '#')
1888             continue;
1889         if (line[0] != '-') {
1890             JLI_ReportErrorMessage(CFG_WARN2, lineno, jvmCfgName);
1891         }
1892         if (cnt >= knownVMsLimit) {
1893             GrowKnownVMs(cnt);
1894         }
1895         line[JLI_StrLen(line)-1] = '\0'; /* remove trailing newline */
1896         tmpPtr = line + JLI_StrCSpn(line, whiteSpace);
1897         if (*tmpPtr == 0) {
1898             JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
1899         } else {
1900             /* Null-terminate this string for JLI_StringDup below */
1901             *tmpPtr++ = 0;
1902             tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
1903             if (*tmpPtr == 0) {
1904                 JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
1905             } else {
1906                 if (!JLI_StrCCmp(tmpPtr, "KNOWN")) {
1907                     vmType = VM_KNOWN;
1908                 } else if (!JLI_StrCCmp(tmpPtr, "ALIASED_TO")) {
1909                     tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
1910                     if (*tmpPtr != 0) {
1911                         tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
1912                     }
1913                     if (*tmpPtr == 0) {
1914                         JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
1915                     } else {
1916                         /* Null terminate altVMName */
1917                         altVMName = tmpPtr;
1918                         tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
1919                         *tmpPtr = 0;
1920                         vmType = VM_ALIASED_TO;
1921                     }
1922                 } else if (!JLI_StrCCmp(tmpPtr, "WARN")) {
1923                     vmType = VM_WARN;
1924                 } else if (!JLI_StrCCmp(tmpPtr, "IGNORE")) {
1925                     vmType = VM_IGNORE;
1926                 } else if (!JLI_StrCCmp(tmpPtr, "ERROR")) {
1927                     vmType = VM_ERROR;
1928                 } else if (!JLI_StrCCmp(tmpPtr, "IF_SERVER_CLASS")) {
1929                     tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
1930                     if (*tmpPtr != 0) {
1931                         tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
1932                     }
1933                     if (*tmpPtr == 0) {
1934                         JLI_ReportErrorMessage(CFG_WARN4, lineno, jvmCfgName);
1935                     } else {
1936                         /* Null terminate server class VM name */
1937                         serverClassVMName = tmpPtr;
1938                         tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
1939                         *tmpPtr = 0;
1940                         vmType = VM_IF_SERVER_CLASS;
1941                     }
1942                 } else {
1943                     JLI_ReportErrorMessage(CFG_WARN5, lineno, &jvmCfgName[0]);
1944                     vmType = VM_KNOWN;
1945                 }
1946             }
1947         }
1948 
1949         JLI_TraceLauncher("jvm.cfg[%d] = ->%s<-\n", cnt, line);
1950         if (vmType != VM_UNKNOWN) {
1951             knownVMs[cnt].name = JLI_StringDup(line);
1952             knownVMs[cnt].flag = vmType;
1953             switch (vmType) {
1954             default:
1955                 break;
1956             case VM_ALIASED_TO:
1957                 knownVMs[cnt].alias = JLI_StringDup(altVMName);
1958                 JLI_TraceLauncher("    name: %s  vmType: %s  alias: %s\n",
1959                    knownVMs[cnt].name, "VM_ALIASED_TO", knownVMs[cnt].alias);
1960                 break;
1961             case VM_IF_SERVER_CLASS:
1962                 knownVMs[cnt].server_class = JLI_StringDup(serverClassVMName);
1963                 JLI_TraceLauncher("    name: %s  vmType: %s  server_class: %s\n",
1964                     knownVMs[cnt].name, "VM_IF_SERVER_CLASS", knownVMs[cnt].server_class);
1965                 break;
1966             }
1967             cnt++;
1968         }
1969     }
1970     fclose(jvmCfg);
1971     knownVMsCount = cnt;
1972 
1973     if (JLI_IsTraceLauncher()) {
1974         end   = CounterGet();
1975         printf("%ld micro seconds to parse jvm.cfg\n",
1976                (long)(jint)Counter2Micros(end-start));
1977     }
1978 
1979     return cnt;
1980 }
1981 
1982 
1983 static void
1984 GrowKnownVMs(int minimum)
1985 {
1986     struct vmdesc* newKnownVMs;
1987     int newMax;
1988 
1989     newMax = (knownVMsLimit == 0 ? INIT_MAX_KNOWN_VMS : (2 * knownVMsLimit));
1990     if (newMax <= minimum) {
1991         newMax = minimum;
1992     }
1993     newKnownVMs = (struct vmdesc*) JLI_MemAlloc(newMax * sizeof(struct vmdesc));
1994     if (knownVMs != NULL) {
1995         memcpy(newKnownVMs, knownVMs, knownVMsLimit * sizeof(struct vmdesc));
1996     }
1997     JLI_MemFree(knownVMs);
1998     knownVMs = newKnownVMs;
1999     knownVMsLimit = newMax;
2000 }
2001 
2002 
2003 /* Returns index of VM or -1 if not found */
2004 static int
2005 KnownVMIndex(const char* name)
2006 {
2007     int i;
2008     if (JLI_StrCCmp(name, "-J") == 0) name += 2;
2009     for (i = 0; i < knownVMsCount; i++) {
2010         if (!JLI_StrCmp(name, knownVMs[i].name)) {
2011             return i;
2012         }
2013     }
2014     return -1;
2015 }
2016 
2017 static void
2018 FreeKnownVMs()
2019 {
2020     int i;
2021     for (i = 0; i < knownVMsCount; i++) {
2022         JLI_MemFree(knownVMs[i].name);
2023         knownVMs[i].name = NULL;
2024     }
2025     JLI_MemFree(knownVMs);
2026 }
2027 
2028 /*
2029  * Displays the splash screen according to the jar file name
2030  * and image file names stored in environment variables
2031  */
2032 void
2033 ShowSplashScreen()
2034 {
2035     const char *jar_name = getenv(SPLASH_JAR_ENV_ENTRY);
2036     const char *file_name = getenv(SPLASH_FILE_ENV_ENTRY);
2037     int data_size;
2038     void *image_data = NULL;
2039     float scale_factor = 1;
2040     char *scaled_splash_name = NULL;
2041     jboolean isImageScaled = JNI_FALSE;
2042     size_t maxScaledImgNameLength = 0;
2043     if (file_name == NULL){
2044         return;
2045     }
2046     maxScaledImgNameLength = DoSplashGetScaledImgNameMaxPstfixLen(file_name);
2047 
2048     scaled_splash_name = JLI_MemAlloc(
2049                             maxScaledImgNameLength * sizeof(char));
2050     isImageScaled = DoSplashGetScaledImageName(jar_name, file_name,
2051                             &scale_factor,
2052                             scaled_splash_name, maxScaledImgNameLength);
2053     if (jar_name) {
2054 
2055         if (isImageScaled) {
2056             image_data = JLI_JarUnpackFile(
2057                     jar_name, scaled_splash_name, &data_size);
2058         }
2059 
2060         if (!image_data) {
2061             scale_factor = 1;
2062             image_data = JLI_JarUnpackFile(
2063                             jar_name, file_name, &data_size);
2064         }
2065         if (image_data) {
2066             DoSplashInit();
2067             DoSplashSetScaleFactor(scale_factor);
2068             DoSplashLoadMemory(image_data, data_size);
2069             JLI_MemFree(image_data);
2070         }
2071     } else {
2072         DoSplashInit();
2073         if (isImageScaled) {
2074             DoSplashSetScaleFactor(scale_factor);
2075             DoSplashLoadFile(scaled_splash_name);
2076         } else {
2077             DoSplashLoadFile(file_name);
2078         }
2079     }
2080     JLI_MemFree(scaled_splash_name);
2081 
2082     DoSplashSetFileJarName(file_name, jar_name);
2083 
2084     /*
2085      * Done with all command line processing and potential re-execs so
2086      * clean up the environment.
2087      */
2088     (void)UnsetEnv(ENV_ENTRY);
2089     (void)UnsetEnv(SPLASH_FILE_ENV_ENTRY);
2090     (void)UnsetEnv(SPLASH_JAR_ENV_ENTRY);
2091 
2092     JLI_MemFree(splash_jar_entry);
2093     JLI_MemFree(splash_file_entry);
2094 
2095 }
2096 
2097 const char*
2098 GetFullVersion()
2099 {
2100     return _fVersion;
2101 }
2102 
2103 const char*
2104 GetProgramName()
2105 {
2106     return _program_name;
2107 }
2108 
2109 const char*
2110 GetLauncherName()
2111 {
2112     return _launcher_name;
2113 }
2114 
2115 jint
2116 GetErgoPolicy()
2117 {
2118     return _ergo_policy;
2119 }
2120 
2121 jboolean
2122 IsJavaArgs()
2123 {
2124     return _is_java_args;
2125 }
2126 
2127 static jboolean
2128 IsWildCardEnabled()
2129 {
2130     return _wc_enabled;
2131 }
2132 
2133 int
2134 ContinueInNewThread(InvocationFunctions* ifn, jlong threadStackSize,
2135                     int argc, char **argv,
2136                     int mode, char *what, int ret)
2137 {
2138 
2139     /*
2140      * If user doesn't specify stack size, check if VM has a preference.
2141      * Note that HotSpot no longer supports JNI_VERSION_1_1 but it will
2142      * return its default stack size through the init args structure.
2143      */
2144     if (threadStackSize == 0) {
2145       struct JDK1_1InitArgs args1_1;
2146       memset((void*)&args1_1, 0, sizeof(args1_1));
2147       args1_1.version = JNI_VERSION_1_1;
2148       ifn->GetDefaultJavaVMInitArgs(&args1_1);  /* ignore return value */
2149       if (args1_1.javaStackSize > 0) {
2150          threadStackSize = args1_1.javaStackSize;
2151       }
2152     }
2153 
2154     { /* Create a new thread to create JVM and invoke main method */
2155       JavaMainArgs args;
2156       int rslt;
2157 
2158       args.argc = argc;
2159       args.argv = argv;
2160       args.mode = mode;
2161       args.what = what;
2162       args.ifn = *ifn;
2163 
2164       rslt = ContinueInNewThread0(JavaMain, threadStackSize, (void*)&args);
2165       /* If the caller has deemed there is an error we
2166        * simply return that, otherwise we return the value of
2167        * the callee
2168        */
2169       return (ret != 0) ? ret : rslt;
2170     }
2171 }
2172 
2173 static void
2174 DumpState()
2175 {
2176     if (!JLI_IsTraceLauncher()) return ;
2177     printf("Launcher state:\n");
2178     printf("\tFirst application arg index: %d\n", JLI_GetAppArgIndex());
2179     printf("\tdebug:%s\n", (JLI_IsTraceLauncher() == JNI_TRUE) ? "on" : "off");
2180     printf("\tjavargs:%s\n", (_is_java_args == JNI_TRUE) ? "on" : "off");
2181     printf("\tprogram name:%s\n", GetProgramName());
2182     printf("\tlauncher name:%s\n", GetLauncherName());
2183     printf("\tjavaw:%s\n", (IsJavaw() == JNI_TRUE) ? "on" : "off");
2184     printf("\tfullversion:%s\n", GetFullVersion());
2185     printf("\tergo_policy:");
2186     switch(GetErgoPolicy()) {
2187         case NEVER_SERVER_CLASS:
2188             printf("NEVER_ACT_AS_A_SERVER_CLASS_MACHINE\n");
2189             break;
2190         case ALWAYS_SERVER_CLASS:
2191             printf("ALWAYS_ACT_AS_A_SERVER_CLASS_MACHINE\n");
2192             break;
2193         default:
2194             printf("DEFAULT_ERGONOMICS_POLICY\n");
2195     }
2196 }
2197 
2198 /*
2199  * Return JNI_TRUE for an option string that has no effect but should
2200  * _not_ be passed on to the vm; return JNI_FALSE otherwise.  On
2201  * Solaris SPARC, this screening needs to be done if:
2202  *    -d32 or -d64 is passed to a binary with an unmatched data model
2203  *    (the exec in CreateExecutionEnvironment removes -d<n> options and points the
2204  *    exec to the proper binary).  In the case of when the data model and the
2205  *    requested version is matched, an exec would not occur, and these options
2206  *    were erroneously passed to the vm.
2207  */
2208 jboolean
2209 RemovableOption(char * option)
2210 {
2211   /*
2212    * Unconditionally remove both -d32 and -d64 options since only
2213    * the last such options has an effect; e.g.
2214    * java -d32 -d64 -d32 -version
2215    * is equivalent to
2216    * java -d32 -version
2217    */
2218 
2219   if( (JLI_StrCCmp(option, "-d32")  == 0 ) ||
2220       (JLI_StrCCmp(option, "-d64")  == 0 ) )
2221     return JNI_TRUE;
2222   else
2223     return JNI_FALSE;
2224 }
2225 
2226 /*
2227  * A utility procedure to always print to stderr
2228  */
2229 void
2230 JLI_ReportMessage(const char* fmt, ...)
2231 {
2232     va_list vl;
2233     va_start(vl, fmt);
2234     vfprintf(stderr, fmt, vl);
2235     fprintf(stderr, "\n");
2236     va_end(vl);
2237 }