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