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