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         kind = IsLauncherMainOption(arg) ? LAUNCHER_MAIN_OPTION
1201                                          : LAUNCHER_OPTION_WITH_ARGUMENT;
1202     } else if (IsModuleOption(arg)) {
1203         kind = VM_LONG_OPTION_WITH_ARGUMENT;
1204         if (has_arg) {
1205             value = *argv;
1206             argv++; --argc;
1207         }
1208 
1209         /*
1210          * Support short form alias
1211          */
1212         if (JLI_StrCmp(arg, "-p") == 0) {
1213             option = "--module-path";
1214         }
1215 
1216     } else if (JLI_StrCCmp(arg, "--") == 0 && (equals = JLI_StrChr(arg, '=')) != NULL) {
1217         value = equals+1;
1218         if (JLI_StrCCmp(arg, "--list-modules=") == 0 ||
1219             JLI_StrCCmp(arg, "--module=") == 0 ||
1220             JLI_StrCCmp(arg, "--class-path=") == 0) {
1221             kind = LAUNCHER_OPTION_WITH_ARGUMENT;
1222         } else {
1223             kind = VM_LONG_OPTION;
1224         }
1225     }
1226 
1227 #ifndef OLD_MODULE_OPTIONS
1228     // for transition to support both old and new syntax
1229     if (JLI_StrCmp(arg, "-modulepath") == 0 ||
1230         JLI_StrCmp(arg, "-mp") == 0) {
1231         option = "--module-path";
1232     } else if (JLI_StrCmp(arg, "-upgrademodulepath") == 0) {
1233         option = "--upgrade-module-path";
1234     } else if (JLI_StrCmp(arg, "-addmods") == 0) {
1235         option = "--add-modules";
1236     } else if (JLI_StrCmp(arg, "-limitmods") == 0) {
1237         option = "--limit-modules";
1238     } else if (JLI_StrCCmp(arg, "-XaddExports:") == 0) {
1239         option = "--add-exports";
1240         value = arg + 13;
1241         kind = VM_LONG_OPTION_WITH_ARGUMENT;
1242     } else if (JLI_StrCCmp(arg, "-XaddReads:") == 0) {
1243         option = "--add-reads";
1244         value = arg + 11;
1245         kind = VM_LONG_OPTION_WITH_ARGUMENT;
1246     } else if (JLI_StrCCmp(arg, "-Xpatch:") == 0) {
1247         option = "--patch-module";
1248         value = arg + 8;
1249         kind = VM_LONG_OPTION_WITH_ARGUMENT;
1250     }
1251 #endif
1252 
1253     *pargc = argc;
1254     *pargv = argv;
1255     *poption = option;
1256     *pvalue = value;
1257     return kind;
1258 }
1259 
1260 /*
1261  * Parses command line arguments.  Returns JNI_FALSE if launcher
1262  * should exit without starting vm, returns JNI_TRUE if vm needs
1263  * to be started to process given options.  *pret (the launcher
1264  * process return value) is set to 0 for a normal exit.
1265  */
1266 static jboolean
1267 ParseArguments(int *pargc, char ***pargv,
1268                int *pmode, char **pwhat,
1269                int *pret, const char *jrepath)
1270 {
1271     int argc = *pargc;
1272     char **argv = *pargv;
1273     int mode = LM_UNKNOWN;
1274     char *arg;
1275 
1276     *pret = 0;
1277 
1278     while ((arg = *argv) != 0 && *arg == '-') {
1279         char *option = NULL;
1280         char *value = NULL;
1281         int kind = GetOpt(&argc, &argv, &option, &value);
1282         jboolean has_arg = value != NULL;
1283 
1284 /*
1285  * Option to set main entry point
1286  */
1287         if (JLI_StrCmp(arg, "-jar") == 0) {
1288             ARG_CHECK(argc, ARG_ERROR2, arg);
1289             mode = LM_JAR;
1290         } else if (JLI_StrCmp(arg, "--module") == 0 ||
1291                    JLI_StrCCmp(arg, "--module=") == 0 ||
1292                    JLI_StrCmp(arg, "-m") == 0) {
1293             REPORT_ERROR (has_arg, ARG_ERROR5, arg);
1294             SetMainModule(value);
1295             mode = LM_MODULE;
1296             if (has_arg) {
1297                *pwhat = value;
1298                 break;
1299             }
1300         } else if (JLI_StrCmp(arg, "--class-path") == 0 ||
1301                    JLI_StrCCmp(arg, "--class-path=") == 0 ||
1302                    JLI_StrCmp(arg, "-classpath") == 0 ||
1303                    JLI_StrCmp(arg, "-cp") == 0) {
1304             REPORT_ERROR (has_arg, ARG_ERROR1, arg);
1305             SetClassPath(value);
1306             mode = LM_CLASS;
1307         } else if (JLI_StrCmp(arg, "--list-modules") == 0 ||
1308                    JLI_StrCCmp(arg, "--list-modules=") == 0) {
1309             listModules = arg;
1310 
1311             // set listModules to --list-modules=<module-names> if argument is specified
1312             if (JLI_StrCmp(arg, "--list-modules") == 0 && has_arg) {
1313                 static const char format[] = "%s=%s";
1314                 size_t buflen = JLI_StrLen(option) + 2 + JLI_StrLen(value);
1315                 listModules = JLI_MemAlloc(buflen);
1316                 JLI_Snprintf(listModules, buflen, format, option, value);
1317             }
1318             return JNI_TRUE;
1319 /*
1320  * Parse white-space options
1321  */
1322         } else if (has_arg) {
1323             if (kind == VM_LONG_OPTION) {
1324                 AddOption(option, NULL);
1325             } else if (kind == VM_LONG_OPTION_WITH_ARGUMENT) {
1326                 AddLongFormOption(option, value);
1327             }
1328 /*
1329  * Error missing argument
1330  */
1331         } else if (!has_arg && IsWhiteSpaceOption(arg)) {
1332             if (JLI_StrCmp(arg, "--module-path") == 0 ||
1333                 JLI_StrCmp(arg, "-p") == 0 ||
1334                 JLI_StrCmp(arg, "--upgrade-module-path") == 0) {
1335                 REPORT_ERROR (has_arg, ARG_ERROR4, arg);
1336             } else if (JLI_StrCmp(arg, "--add-modules") == 0 ||
1337                        JLI_StrCmp(arg, "--limit-modules") == 0 ||
1338                        JLI_StrCmp(arg, "--add-exports") == 0 ||
1339                        JLI_StrCmp(arg, "--add-reads") == 0 ||
1340                        JLI_StrCmp(arg, "--patch-module") == 0) {
1341                 REPORT_ERROR (has_arg, ARG_ERROR6, arg);
1342             }
1343 #ifndef OLD_MODULE_OPTIONS
1344             else if (JLI_StrCmp(arg, "-modulepath") == 0 ||
1345                      JLI_StrCmp(arg, "-mp") == 0 ||
1346                      JLI_StrCmp(arg, "-upgrademodulepath") == 0) {
1347                 REPORT_ERROR (has_arg, ARG_ERROR4, arg);
1348             } else if (JLI_StrCmp(arg, "-addmods") == 0 ||
1349                        JLI_StrCmp(arg, "-limitmods") == 0) {
1350                 REPORT_ERROR (has_arg, ARG_ERROR6, arg);
1351             }
1352 #endif
1353 /*
1354  * The following cases will cause the argument parsing to stop
1355  */
1356         } else if (JLI_StrCmp(arg, "--help") == 0 ||
1357                    JLI_StrCmp(arg, "-help") == 0 ||
1358                    JLI_StrCmp(arg, "-h") == 0 ||
1359                    JLI_StrCmp(arg, "-?") == 0) {
1360             printUsage = JNI_TRUE;
1361             return JNI_TRUE;
1362         } else if (JLI_StrCmp(arg, "-version") == 0) {
1363             printVersion = JNI_TRUE;
1364             return JNI_TRUE;
1365         } else if (JLI_StrCmp(arg, "-showversion") == 0) {
1366             showVersion = JNI_TRUE;
1367         } else if (JLI_StrCmp(arg, "--dry-run") == 0) {
1368             dryRun = JNI_TRUE;
1369         } else if (JLI_StrCmp(arg, "-X") == 0) {
1370             printXUsage = JNI_TRUE;
1371             return JNI_TRUE;
1372 /*
1373  * The following case checks for -XshowSettings OR -XshowSetting:SUBOPT.
1374  * In the latter case, any SUBOPT value not recognized will default to "all"
1375  */
1376         } else if (JLI_StrCmp(arg, "-XshowSettings") == 0 ||
1377                    JLI_StrCCmp(arg, "-XshowSettings:") == 0) {
1378             showSettings = arg;
1379         } else if (JLI_StrCmp(arg, "-Xdiag") == 0) {
1380             AddOption("-Dsun.java.launcher.diag=true", NULL);
1381             AddOption("-Djdk.launcher.traceResolver=true", NULL);
1382         } else if (JLI_StrCmp(arg, "-Xdiag:resolver") == 0) {
1383             AddOption("-Djdk.launcher.traceResolver=true", NULL);
1384 /*
1385  * The following case provide backward compatibility with old-style
1386  * command line options.
1387  */
1388         } else if (JLI_StrCmp(arg, "-fullversion") == 0) {
1389             JLI_ReportMessage("%s full version \"%s\"", _launcher_name, GetFullVersion());
1390             return JNI_FALSE;
1391         } else if (JLI_StrCmp(arg, "-verbosegc") == 0) {
1392             AddOption("-verbose:gc", NULL);
1393         } else if (JLI_StrCmp(arg, "-t") == 0) {
1394             AddOption("-Xt", NULL);
1395         } else if (JLI_StrCmp(arg, "-tm") == 0) {
1396             AddOption("-Xtm", NULL);
1397         } else if (JLI_StrCmp(arg, "-debug") == 0) {
1398             AddOption("-Xdebug", NULL);
1399         } else if (JLI_StrCmp(arg, "-noclassgc") == 0) {
1400             AddOption("-Xnoclassgc", NULL);
1401         } else if (JLI_StrCmp(arg, "-Xfuture") == 0) {
1402             AddOption("-Xverify:all", NULL);
1403         } else if (JLI_StrCmp(arg, "-verify") == 0) {
1404             AddOption("-Xverify:all", NULL);
1405         } else if (JLI_StrCmp(arg, "-verifyremote") == 0) {
1406             AddOption("-Xverify:remote", NULL);
1407         } else if (JLI_StrCmp(arg, "-noverify") == 0) {
1408             AddOption("-Xverify:none", NULL);
1409         } else if (JLI_StrCCmp(arg, "-ss") == 0 ||
1410                    JLI_StrCCmp(arg, "-oss") == 0 ||
1411                    JLI_StrCCmp(arg, "-ms") == 0 ||
1412                    JLI_StrCCmp(arg, "-mx") == 0) {
1413             char *tmp = JLI_MemAlloc(JLI_StrLen(arg) + 6);
1414             sprintf(tmp, "-X%s", arg + 1); /* skip '-' */
1415             AddOption(tmp, NULL);
1416         } else if (JLI_StrCmp(arg, "-checksource") == 0 ||
1417                    JLI_StrCmp(arg, "-cs") == 0 ||
1418                    JLI_StrCmp(arg, "-noasyncgc") == 0) {
1419             /* No longer supported */
1420             JLI_ReportErrorMessage(ARG_WARN, arg);
1421         } else if (JLI_StrCCmp(arg, "-splash:") == 0) {
1422             ; /* Ignore machine independent options already handled */
1423         } else if (ProcessPlatformOption(arg)) {
1424             ; /* Processing of platform dependent options */
1425         } else if (RemovableOption(arg)) {
1426             ; /* Do not pass option to vm. */
1427         } else {
1428             /* java.class.path set on the command line */
1429             if (JLI_StrCCmp(arg, "-Djava.class.path=") == 0) {
1430                 _have_classpath = JNI_TRUE;
1431             }
1432             AddOption(arg, NULL);
1433         }
1434     }
1435 
1436     if (*pwhat == NULL && --argc >= 0) {
1437         *pwhat = *argv++;
1438     }
1439 
1440     if (*pwhat == NULL) {
1441         *pret = 1;
1442     } else if (mode == LM_UNKNOWN) {
1443         /* default to LM_CLASS if -m, -jar and -cp options are
1444          * not specified */
1445         if (!_have_classpath) {
1446             SetClassPath(".");
1447         }
1448         mode = LM_CLASS;
1449     }
1450 
1451     if (argc >= 0) {
1452         *pargc = argc;
1453         *pargv = argv;
1454     }
1455 
1456     *pmode = mode;
1457 
1458     return JNI_TRUE;
1459 }
1460 
1461 /*
1462  * Initializes the Java Virtual Machine. Also frees options array when
1463  * finished.
1464  */
1465 static jboolean
1466 InitializeJVM(JavaVM **pvm, JNIEnv **penv, InvocationFunctions *ifn)
1467 {
1468     JavaVMInitArgs args;
1469     jint r;
1470 
1471     memset(&args, 0, sizeof(args));
1472     args.version  = JNI_VERSION_1_2;
1473     args.nOptions = numOptions;
1474     args.options  = options;
1475     args.ignoreUnrecognized = JNI_FALSE;
1476 
1477     if (JLI_IsTraceLauncher()) {
1478         int i = 0;
1479         printf("JavaVM args:\n    ");
1480         printf("version 0x%08lx, ", (long)args.version);
1481         printf("ignoreUnrecognized is %s, ",
1482                args.ignoreUnrecognized ? "JNI_TRUE" : "JNI_FALSE");
1483         printf("nOptions is %ld\n", (long)args.nOptions);
1484         for (i = 0; i < numOptions; i++)
1485             printf("    option[%2d] = '%s'\n",
1486                    i, args.options[i].optionString);
1487     }
1488 
1489     r = ifn->CreateJavaVM(pvm, (void **)penv, &args);
1490     JLI_MemFree(options);
1491     return r == JNI_OK;
1492 }
1493 
1494 static jclass helperClass = NULL;
1495 
1496 jclass
1497 GetLauncherHelperClass(JNIEnv *env)
1498 {
1499     if (helperClass == NULL) {
1500         NULL_CHECK0(helperClass = FindBootStrapClass(env,
1501                 "sun/launcher/LauncherHelper"));
1502     }
1503     return helperClass;
1504 }
1505 
1506 static jmethodID makePlatformStringMID = NULL;
1507 /*
1508  * Returns a new Java string object for the specified platform string.
1509  */
1510 static jstring
1511 NewPlatformString(JNIEnv *env, char *s)
1512 {
1513     int len = (int)JLI_StrLen(s);
1514     jbyteArray ary;
1515     jclass cls = GetLauncherHelperClass(env);
1516     NULL_CHECK0(cls);
1517     if (s == NULL)
1518         return 0;
1519 
1520     ary = (*env)->NewByteArray(env, len);
1521     if (ary != 0) {
1522         jstring str = 0;
1523         (*env)->SetByteArrayRegion(env, ary, 0, len, (jbyte *)s);
1524         if (!(*env)->ExceptionOccurred(env)) {
1525             if (makePlatformStringMID == NULL) {
1526                 NULL_CHECK0(makePlatformStringMID = (*env)->GetStaticMethodID(env,
1527                         cls, "makePlatformString", "(Z[B)Ljava/lang/String;"));
1528             }
1529             str = (*env)->CallStaticObjectMethod(env, cls,
1530                     makePlatformStringMID, USE_STDERR, ary);
1531             (*env)->DeleteLocalRef(env, ary);
1532             return str;
1533         }
1534     }
1535     return 0;
1536 }
1537 
1538 /*
1539  * Returns a new array of Java string objects for the specified
1540  * array of platform strings.
1541  */
1542 jobjectArray
1543 NewPlatformStringArray(JNIEnv *env, char **strv, int strc)
1544 {
1545     jarray cls;
1546     jarray ary;
1547     int i;
1548 
1549     NULL_CHECK0(cls = FindBootStrapClass(env, "java/lang/String"));
1550     NULL_CHECK0(ary = (*env)->NewObjectArray(env, strc, cls, 0));
1551     for (i = 0; i < strc; i++) {
1552         jstring str = NewPlatformString(env, *strv++);
1553         NULL_CHECK0(str);
1554         (*env)->SetObjectArrayElement(env, ary, i, str);
1555         (*env)->DeleteLocalRef(env, str);
1556     }
1557     return ary;
1558 }
1559 
1560 /*
1561  * Loads a class and verifies that the main class is present and it is ok to
1562  * call it for more details refer to the java implementation.
1563  */
1564 static jclass
1565 LoadMainClass(JNIEnv *env, int mode, char *name)
1566 {
1567     jmethodID mid;
1568     jstring str;
1569     jobject result;
1570     jlong start, end;
1571     jclass cls = GetLauncherHelperClass(env);
1572     NULL_CHECK0(cls);
1573     if (JLI_IsTraceLauncher()) {
1574         start = CounterGet();
1575     }
1576     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1577                 "checkAndLoadMain",
1578                 "(ZILjava/lang/String;)Ljava/lang/Class;"));
1579 
1580     NULL_CHECK0(str = NewPlatformString(env, name));
1581     NULL_CHECK0(result = (*env)->CallStaticObjectMethod(env, cls, mid,
1582                                                         USE_STDERR, mode, str));
1583 
1584     if (JLI_IsTraceLauncher()) {
1585         end   = CounterGet();
1586         printf("%ld micro seconds to load main class\n",
1587                (long)(jint)Counter2Micros(end-start));
1588         printf("----%s----\n", JLDEBUG_ENV_ENTRY);
1589     }
1590 
1591     return (jclass)result;
1592 }
1593 
1594 static jclass
1595 GetApplicationClass(JNIEnv *env)
1596 {
1597     jmethodID mid;
1598     jclass cls = GetLauncherHelperClass(env);
1599     NULL_CHECK0(cls);
1600     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1601                 "getApplicationClass",
1602                 "()Ljava/lang/Class;"));
1603 
1604     return (*env)->CallStaticObjectMethod(env, cls, mid);
1605 }
1606 
1607 /*
1608  * For tools, convert command line args thus:
1609  *   javac -cp foo:foo/"*" -J-ms32m ...
1610  *   java -ms32m -cp JLI_WildcardExpandClasspath(foo:foo/"*") ...
1611  *
1612  * Takes 4 parameters, and returns the populated arguments
1613  */
1614 static void
1615 TranslateApplicationArgs(int jargc, const char **jargv, int *pargc, char ***pargv)
1616 {
1617     int argc = *pargc;
1618     char **argv = *pargv;
1619     int nargc = argc + jargc;
1620     char **nargv = JLI_MemAlloc((nargc + 1) * sizeof(char *));
1621     int i;
1622 
1623     *pargc = nargc;
1624     *pargv = nargv;
1625 
1626     /* Copy the VM arguments (i.e. prefixed with -J) */
1627     for (i = 0; i < jargc; i++) {
1628         const char *arg = jargv[i];
1629         if (arg[0] == '-' && arg[1] == 'J') {
1630             *nargv++ = ((arg + 2) == NULL) ? NULL : JLI_StringDup(arg + 2);
1631         }
1632     }
1633 
1634     for (i = 0; i < argc; i++) {
1635         char *arg = argv[i];
1636         if (arg[0] == '-' && arg[1] == 'J') {
1637             if (arg[2] == '\0') {
1638                 JLI_ReportErrorMessage(ARG_ERROR3);
1639                 exit(1);
1640             }
1641             *nargv++ = arg + 2;
1642         }
1643     }
1644 
1645     /* Copy the rest of the arguments */
1646     for (i = 0; i < jargc ; i++) {
1647         const char *arg = jargv[i];
1648         if (arg[0] != '-' || arg[1] != 'J') {
1649             *nargv++ = (arg == NULL) ? NULL : JLI_StringDup(arg);
1650         }
1651     }
1652     for (i = 0; i < argc; i++) {
1653         char *arg = argv[i];
1654         if (arg[0] == '-') {
1655             if (arg[1] == 'J')
1656                 continue;
1657             if (IsWildCardEnabled() && arg[1] == 'c'
1658                 && (JLI_StrCmp(arg, "-cp") == 0 ||
1659                     JLI_StrCmp(arg, "-classpath") == 0)
1660                 && i < argc - 1) {
1661                 *nargv++ = arg;
1662                 *nargv++ = (char *) JLI_WildcardExpandClasspath(argv[i+1]);
1663                 i++;
1664                 continue;
1665             }
1666         }
1667         *nargv++ = arg;
1668     }
1669     *nargv = 0;
1670 }
1671 
1672 /*
1673  * For our tools, we try to add 3 VM options:
1674  *      -Denv.class.path=<envcp>
1675  *      -Dapplication.home=<apphome>
1676  *      -Djava.class.path=<appcp>
1677  * <envcp>   is the user's setting of CLASSPATH -- for instance the user
1678  *           tells javac where to find binary classes through this environment
1679  *           variable.  Notice that users will be able to compile against our
1680  *           tools classes (sun.tools.javac.Main) only if they explicitly add
1681  *           tools.jar to CLASSPATH.
1682  * <apphome> is the directory where the application is installed.
1683  * <appcp>   is the classpath to where our apps' classfiles are.
1684  */
1685 static jboolean
1686 AddApplicationOptions(int cpathc, const char **cpathv)
1687 {
1688     char *envcp, *appcp, *apphome;
1689     char home[MAXPATHLEN]; /* application home */
1690     char separator[] = { PATH_SEPARATOR, '\0' };
1691     int size, i;
1692 
1693     {
1694         const char *s = getenv("CLASSPATH");
1695         if (s) {
1696             s = (char *) JLI_WildcardExpandClasspath(s);
1697             /* 40 for -Denv.class.path= */
1698             if (JLI_StrLen(s) + 40 > JLI_StrLen(s)) { // Safeguard from overflow
1699                 envcp = (char *)JLI_MemAlloc(JLI_StrLen(s) + 40);
1700                 sprintf(envcp, "-Denv.class.path=%s", s);
1701                 AddOption(envcp, NULL);
1702             }
1703         }
1704     }
1705 
1706     if (!GetApplicationHome(home, sizeof(home))) {
1707         JLI_ReportErrorMessage(CFG_ERROR5);
1708         return JNI_FALSE;
1709     }
1710 
1711     /* 40 for '-Dapplication.home=' */
1712     apphome = (char *)JLI_MemAlloc(JLI_StrLen(home) + 40);
1713     sprintf(apphome, "-Dapplication.home=%s", home);
1714     AddOption(apphome, NULL);
1715 
1716     /* How big is the application's classpath? */
1717     size = 40;                                 /* 40: "-Djava.class.path=" */
1718     for (i = 0; i < cpathc; i++) {
1719         size += (int)JLI_StrLen(home) + (int)JLI_StrLen(cpathv[i]) + 1; /* 1: separator */
1720     }
1721     appcp = (char *)JLI_MemAlloc(size + 1);
1722     JLI_StrCpy(appcp, "-Djava.class.path=");
1723     for (i = 0; i < cpathc; i++) {
1724         JLI_StrCat(appcp, home);                        /* c:\program files\myapp */
1725         JLI_StrCat(appcp, cpathv[i]);           /* \lib\myapp.jar         */
1726         JLI_StrCat(appcp, separator);           /* ;                      */
1727     }
1728     appcp[JLI_StrLen(appcp)-1] = '\0';  /* remove trailing path separator */
1729     AddOption(appcp, NULL);
1730     return JNI_TRUE;
1731 }
1732 
1733 /*
1734  * inject the -Dsun.java.command pseudo property into the args structure
1735  * this pseudo property is used in the HotSpot VM to expose the
1736  * Java class name and arguments to the main method to the VM. The
1737  * HotSpot VM uses this pseudo property to store the Java class name
1738  * (or jar file name) and the arguments to the class's main method
1739  * to the instrumentation memory region. The sun.java.command pseudo
1740  * property is not exported by HotSpot to the Java layer.
1741  */
1742 void
1743 SetJavaCommandLineProp(char *what, int argc, char **argv)
1744 {
1745 
1746     int i = 0;
1747     size_t len = 0;
1748     char* javaCommand = NULL;
1749     char* dashDstr = "-Dsun.java.command=";
1750 
1751     if (what == NULL) {
1752         /* unexpected, one of these should be set. just return without
1753          * setting the property
1754          */
1755         return;
1756     }
1757 
1758     /* determine the amount of memory to allocate assuming
1759      * the individual components will be space separated
1760      */
1761     len = JLI_StrLen(what);
1762     for (i = 0; i < argc; i++) {
1763         len += JLI_StrLen(argv[i]) + 1;
1764     }
1765 
1766     /* allocate the memory */
1767     javaCommand = (char*) JLI_MemAlloc(len + JLI_StrLen(dashDstr) + 1);
1768 
1769     /* build the -D string */
1770     *javaCommand = '\0';
1771     JLI_StrCat(javaCommand, dashDstr);
1772     JLI_StrCat(javaCommand, what);
1773 
1774     for (i = 0; i < argc; i++) {
1775         /* the components of the string are space separated. In
1776          * the case of embedded white space, the relationship of
1777          * the white space separated components to their true
1778          * positional arguments will be ambiguous. This issue may
1779          * be addressed in a future release.
1780          */
1781         JLI_StrCat(javaCommand, " ");
1782         JLI_StrCat(javaCommand, argv[i]);
1783     }
1784 
1785     AddOption(javaCommand, NULL);
1786 }
1787 
1788 /*
1789  * JVM would like to know if it's created by a standard Sun launcher, or by
1790  * user native application, the following property indicates the former.
1791  */
1792 void
1793 SetJavaLauncherProp() {
1794   AddOption("-Dsun.java.launcher=SUN_STANDARD", NULL);
1795 }
1796 
1797 /*
1798  * Prints the version information from the java.version and other properties.
1799  */
1800 static void
1801 PrintJavaVersion(JNIEnv *env, jboolean extraLF)
1802 {
1803     jclass ver;
1804     jmethodID print;
1805 
1806     NULL_CHECK(ver = FindBootStrapClass(env, "java/lang/VersionProps"));
1807     NULL_CHECK(print = (*env)->GetStaticMethodID(env,
1808                                                  ver,
1809                                                  (extraLF == JNI_TRUE) ? "println" : "print",
1810                                                  "()V"
1811                                                  )
1812               );
1813 
1814     (*env)->CallStaticVoidMethod(env, ver, print);
1815 }
1816 
1817 /*
1818  * Prints all the Java settings, see the java implementation for more details.
1819  */
1820 static void
1821 ShowSettings(JNIEnv *env, char *optString)
1822 {
1823     jmethodID showSettingsID;
1824     jstring joptString;
1825     jclass cls = GetLauncherHelperClass(env);
1826     NULL_CHECK(cls);
1827     NULL_CHECK(showSettingsID = (*env)->GetStaticMethodID(env, cls,
1828             "showSettings", "(ZLjava/lang/String;JJJZ)V"));
1829     NULL_CHECK(joptString = (*env)->NewStringUTF(env, optString));
1830     (*env)->CallStaticVoidMethod(env, cls, showSettingsID,
1831                                  USE_STDERR,
1832                                  joptString,
1833                                  (jlong)initialHeapSize,
1834                                  (jlong)maxHeapSize,
1835                                  (jlong)threadStackSize,
1836                                  ServerClassMachine());
1837 }
1838 
1839 /**
1840  * List modules supported by the runtime
1841  */
1842 static void
1843 ListModules(JNIEnv *env, char *optString)
1844 {
1845     jmethodID listModulesID;
1846     jstring joptString = NULL;
1847     jclass cls = GetLauncherHelperClass(env);
1848     NULL_CHECK(cls);
1849     NULL_CHECK(listModulesID = (*env)->GetStaticMethodID(env, cls,
1850             "listModules", "(ZLjava/lang/String;)V"));
1851     NULL_CHECK(joptString = (*env)->NewStringUTF(env, optString));
1852     (*env)->CallStaticVoidMethod(env, cls, listModulesID,
1853                                  USE_STDERR,
1854                                  joptString);
1855 }
1856 
1857 /*
1858  * Prints default usage or the Xusage message, see sun.launcher.LauncherHelper.java
1859  */
1860 static void
1861 PrintUsage(JNIEnv* env, jboolean doXUsage)
1862 {
1863   jmethodID initHelp, vmSelect, vmSynonym, vmErgo, printHelp, printXUsageMessage;
1864   jstring jprogname, vm1, vm2;
1865   int i;
1866   jclass cls = GetLauncherHelperClass(env);
1867   NULL_CHECK(cls);
1868   if (doXUsage) {
1869     NULL_CHECK(printXUsageMessage = (*env)->GetStaticMethodID(env, cls,
1870                                         "printXUsageMessage", "(Z)V"));
1871     (*env)->CallStaticVoidMethod(env, cls, printXUsageMessage, USE_STDERR);
1872   } else {
1873     NULL_CHECK(initHelp = (*env)->GetStaticMethodID(env, cls,
1874                                         "initHelpMessage", "(Ljava/lang/String;)V"));
1875 
1876     NULL_CHECK(vmSelect = (*env)->GetStaticMethodID(env, cls, "appendVmSelectMessage",
1877                                         "(Ljava/lang/String;Ljava/lang/String;)V"));
1878 
1879     NULL_CHECK(vmSynonym = (*env)->GetStaticMethodID(env, cls,
1880                                         "appendVmSynonymMessage",
1881                                         "(Ljava/lang/String;Ljava/lang/String;)V"));
1882     NULL_CHECK(vmErgo = (*env)->GetStaticMethodID(env, cls,
1883                                         "appendVmErgoMessage", "(ZLjava/lang/String;)V"));
1884 
1885     NULL_CHECK(printHelp = (*env)->GetStaticMethodID(env, cls,
1886                                         "printHelpMessage", "(Z)V"));
1887 
1888     NULL_CHECK(jprogname = (*env)->NewStringUTF(env, _program_name));
1889 
1890     /* Initialize the usage message with the usual preamble */
1891     (*env)->CallStaticVoidMethod(env, cls, initHelp, jprogname);
1892     CHECK_EXCEPTION_RETURN();
1893 
1894 
1895     /* Assemble the other variant part of the usage */
1896     if ((knownVMs[0].flag == VM_KNOWN) ||
1897         (knownVMs[0].flag == VM_IF_SERVER_CLASS)) {
1898       NULL_CHECK(vm1 = (*env)->NewStringUTF(env, knownVMs[0].name));
1899       NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[0].name+1));
1900       (*env)->CallStaticVoidMethod(env, cls, vmSelect, vm1, vm2);
1901       CHECK_EXCEPTION_RETURN();
1902     }
1903     for (i=1; i<knownVMsCount; i++) {
1904       if (knownVMs[i].flag == VM_KNOWN) {
1905         NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
1906         NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].name+1));
1907         (*env)->CallStaticVoidMethod(env, cls, vmSelect, vm1, vm2);
1908         CHECK_EXCEPTION_RETURN();
1909       }
1910     }
1911     for (i=1; i<knownVMsCount; i++) {
1912       if (knownVMs[i].flag == VM_ALIASED_TO) {
1913         NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
1914         NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].alias+1));
1915         (*env)->CallStaticVoidMethod(env, cls, vmSynonym, vm1, vm2);
1916         CHECK_EXCEPTION_RETURN();
1917       }
1918     }
1919 
1920     /* The first known VM is the default */
1921     {
1922       jboolean isServerClassMachine = ServerClassMachine();
1923 
1924       const char* defaultVM  =  knownVMs[0].name+1;
1925       if ((knownVMs[0].flag == VM_IF_SERVER_CLASS) && isServerClassMachine) {
1926         defaultVM = knownVMs[0].server_class+1;
1927       }
1928 
1929       NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, defaultVM));
1930       (*env)->CallStaticVoidMethod(env, cls, vmErgo, isServerClassMachine,  vm1);
1931       CHECK_EXCEPTION_RETURN();
1932     }
1933 
1934     /* Complete the usage message and print to stderr*/
1935     (*env)->CallStaticVoidMethod(env, cls, printHelp, USE_STDERR);
1936   }
1937   return;
1938 }
1939 
1940 /*
1941  * Read the jvm.cfg file and fill the knownJVMs[] array.
1942  *
1943  * The functionality of the jvm.cfg file is subject to change without
1944  * notice and the mechanism will be removed in the future.
1945  *
1946  * The lexical structure of the jvm.cfg file is as follows:
1947  *
1948  *     jvmcfg         :=  { vmLine }
1949  *     vmLine         :=  knownLine
1950  *                    |   aliasLine
1951  *                    |   warnLine
1952  *                    |   ignoreLine
1953  *                    |   errorLine
1954  *                    |   predicateLine
1955  *                    |   commentLine
1956  *     knownLine      :=  flag  "KNOWN"                  EOL
1957  *     warnLine       :=  flag  "WARN"                   EOL
1958  *     ignoreLine     :=  flag  "IGNORE"                 EOL
1959  *     errorLine      :=  flag  "ERROR"                  EOL
1960  *     aliasLine      :=  flag  "ALIASED_TO"       flag  EOL
1961  *     predicateLine  :=  flag  "IF_SERVER_CLASS"  flag  EOL
1962  *     commentLine    :=  "#" text                       EOL
1963  *     flag           :=  "-" identifier
1964  *
1965  * The semantics are that when someone specifies a flag on the command line:
1966  * - if the flag appears on a knownLine, then the identifier is used as
1967  *   the name of the directory holding the JVM library (the name of the JVM).
1968  * - if the flag appears as the first flag on an aliasLine, the identifier
1969  *   of the second flag is used as the name of the JVM.
1970  * - if the flag appears on a warnLine, the identifier is used as the
1971  *   name of the JVM, but a warning is generated.
1972  * - if the flag appears on an ignoreLine, the identifier is recognized as the
1973  *   name of a JVM, but the identifier is ignored and the default vm used
1974  * - if the flag appears on an errorLine, an error is generated.
1975  * - if the flag appears as the first flag on a predicateLine, and
1976  *   the machine on which you are running passes the predicate indicated,
1977  *   then the identifier of the second flag is used as the name of the JVM,
1978  *   otherwise the identifier of the first flag is used as the name of the JVM.
1979  * If no flag is given on the command line, the first vmLine of the jvm.cfg
1980  * file determines the name of the JVM.
1981  * PredicateLines are only interpreted on first vmLine of a jvm.cfg file,
1982  * since they only make sense if someone hasn't specified the name of the
1983  * JVM on the command line.
1984  *
1985  * The intent of the jvm.cfg file is to allow several JVM libraries to
1986  * be installed in different subdirectories of a single JRE installation,
1987  * for space-savings and convenience in testing.
1988  * The intent is explicitly not to provide a full aliasing or predicate
1989  * mechanism.
1990  */
1991 jint
1992 ReadKnownVMs(const char *jvmCfgName, jboolean speculative)
1993 {
1994     FILE *jvmCfg;
1995     char line[MAXPATHLEN+20];
1996     int cnt = 0;
1997     int lineno = 0;
1998     jlong start, end;
1999     int vmType;
2000     char *tmpPtr;
2001     char *altVMName = NULL;
2002     char *serverClassVMName = NULL;
2003     static char *whiteSpace = " \t";
2004     if (JLI_IsTraceLauncher()) {
2005         start = CounterGet();
2006     }
2007 
2008     jvmCfg = fopen(jvmCfgName, "r");
2009     if (jvmCfg == NULL) {
2010       if (!speculative) {
2011         JLI_ReportErrorMessage(CFG_ERROR6, jvmCfgName);
2012         exit(1);
2013       } else {
2014         return -1;
2015       }
2016     }
2017     while (fgets(line, sizeof(line), jvmCfg) != NULL) {
2018         vmType = VM_UNKNOWN;
2019         lineno++;
2020         if (line[0] == '#')
2021             continue;
2022         if (line[0] != '-') {
2023             JLI_ReportErrorMessage(CFG_WARN2, lineno, jvmCfgName);
2024         }
2025         if (cnt >= knownVMsLimit) {
2026             GrowKnownVMs(cnt);
2027         }
2028         line[JLI_StrLen(line)-1] = '\0'; /* remove trailing newline */
2029         tmpPtr = line + JLI_StrCSpn(line, whiteSpace);
2030         if (*tmpPtr == 0) {
2031             JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2032         } else {
2033             /* Null-terminate this string for JLI_StringDup below */
2034             *tmpPtr++ = 0;
2035             tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
2036             if (*tmpPtr == 0) {
2037                 JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2038             } else {
2039                 if (!JLI_StrCCmp(tmpPtr, "KNOWN")) {
2040                     vmType = VM_KNOWN;
2041                 } else if (!JLI_StrCCmp(tmpPtr, "ALIASED_TO")) {
2042                     tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
2043                     if (*tmpPtr != 0) {
2044                         tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
2045                     }
2046                     if (*tmpPtr == 0) {
2047                         JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2048                     } else {
2049                         /* Null terminate altVMName */
2050                         altVMName = tmpPtr;
2051                         tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
2052                         *tmpPtr = 0;
2053                         vmType = VM_ALIASED_TO;
2054                     }
2055                 } else if (!JLI_StrCCmp(tmpPtr, "WARN")) {
2056                     vmType = VM_WARN;
2057                 } else if (!JLI_StrCCmp(tmpPtr, "IGNORE")) {
2058                     vmType = VM_IGNORE;
2059                 } else if (!JLI_StrCCmp(tmpPtr, "ERROR")) {
2060                     vmType = VM_ERROR;
2061                 } else if (!JLI_StrCCmp(tmpPtr, "IF_SERVER_CLASS")) {
2062                     tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
2063                     if (*tmpPtr != 0) {
2064                         tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
2065                     }
2066                     if (*tmpPtr == 0) {
2067                         JLI_ReportErrorMessage(CFG_WARN4, lineno, jvmCfgName);
2068                     } else {
2069                         /* Null terminate server class VM name */
2070                         serverClassVMName = tmpPtr;
2071                         tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
2072                         *tmpPtr = 0;
2073                         vmType = VM_IF_SERVER_CLASS;
2074                     }
2075                 } else {
2076                     JLI_ReportErrorMessage(CFG_WARN5, lineno, &jvmCfgName[0]);
2077                     vmType = VM_KNOWN;
2078                 }
2079             }
2080         }
2081 
2082         JLI_TraceLauncher("jvm.cfg[%d] = ->%s<-\n", cnt, line);
2083         if (vmType != VM_UNKNOWN) {
2084             knownVMs[cnt].name = JLI_StringDup(line);
2085             knownVMs[cnt].flag = vmType;
2086             switch (vmType) {
2087             default:
2088                 break;
2089             case VM_ALIASED_TO:
2090                 knownVMs[cnt].alias = JLI_StringDup(altVMName);
2091                 JLI_TraceLauncher("    name: %s  vmType: %s  alias: %s\n",
2092                    knownVMs[cnt].name, "VM_ALIASED_TO", knownVMs[cnt].alias);
2093                 break;
2094             case VM_IF_SERVER_CLASS:
2095                 knownVMs[cnt].server_class = JLI_StringDup(serverClassVMName);
2096                 JLI_TraceLauncher("    name: %s  vmType: %s  server_class: %s\n",
2097                     knownVMs[cnt].name, "VM_IF_SERVER_CLASS", knownVMs[cnt].server_class);
2098                 break;
2099             }
2100             cnt++;
2101         }
2102     }
2103     fclose(jvmCfg);
2104     knownVMsCount = cnt;
2105 
2106     if (JLI_IsTraceLauncher()) {
2107         end   = CounterGet();
2108         printf("%ld micro seconds to parse jvm.cfg\n",
2109                (long)(jint)Counter2Micros(end-start));
2110     }
2111 
2112     return cnt;
2113 }
2114 
2115 
2116 static void
2117 GrowKnownVMs(int minimum)
2118 {
2119     struct vmdesc* newKnownVMs;
2120     int newMax;
2121 
2122     newMax = (knownVMsLimit == 0 ? INIT_MAX_KNOWN_VMS : (2 * knownVMsLimit));
2123     if (newMax <= minimum) {
2124         newMax = minimum;
2125     }
2126     newKnownVMs = (struct vmdesc*) JLI_MemAlloc(newMax * sizeof(struct vmdesc));
2127     if (knownVMs != NULL) {
2128         memcpy(newKnownVMs, knownVMs, knownVMsLimit * sizeof(struct vmdesc));
2129     }
2130     JLI_MemFree(knownVMs);
2131     knownVMs = newKnownVMs;
2132     knownVMsLimit = newMax;
2133 }
2134 
2135 
2136 /* Returns index of VM or -1 if not found */
2137 static int
2138 KnownVMIndex(const char* name)
2139 {
2140     int i;
2141     if (JLI_StrCCmp(name, "-J") == 0) name += 2;
2142     for (i = 0; i < knownVMsCount; i++) {
2143         if (!JLI_StrCmp(name, knownVMs[i].name)) {
2144             return i;
2145         }
2146     }
2147     return -1;
2148 }
2149 
2150 static void
2151 FreeKnownVMs()
2152 {
2153     int i;
2154     for (i = 0; i < knownVMsCount; i++) {
2155         JLI_MemFree(knownVMs[i].name);
2156         knownVMs[i].name = NULL;
2157     }
2158     JLI_MemFree(knownVMs);
2159 }
2160 
2161 /*
2162  * Displays the splash screen according to the jar file name
2163  * and image file names stored in environment variables
2164  */
2165 void
2166 ShowSplashScreen()
2167 {
2168     const char *jar_name = getenv(SPLASH_JAR_ENV_ENTRY);
2169     const char *file_name = getenv(SPLASH_FILE_ENV_ENTRY);
2170     int data_size;
2171     void *image_data = NULL;
2172     float scale_factor = 1;
2173     char *scaled_splash_name = NULL;
2174     jboolean isImageScaled = JNI_FALSE;
2175     size_t maxScaledImgNameLength = 0;
2176     if (file_name == NULL){
2177         return;
2178     }
2179     maxScaledImgNameLength = DoSplashGetScaledImgNameMaxPstfixLen(file_name);
2180 
2181     scaled_splash_name = JLI_MemAlloc(
2182                             maxScaledImgNameLength * sizeof(char));
2183     isImageScaled = DoSplashGetScaledImageName(jar_name, file_name,
2184                             &scale_factor,
2185                             scaled_splash_name, maxScaledImgNameLength);
2186     if (jar_name) {
2187 
2188         if (isImageScaled) {
2189             image_data = JLI_JarUnpackFile(
2190                     jar_name, scaled_splash_name, &data_size);
2191         }
2192 
2193         if (!image_data) {
2194             scale_factor = 1;
2195             image_data = JLI_JarUnpackFile(
2196                             jar_name, file_name, &data_size);
2197         }
2198         if (image_data) {
2199             DoSplashInit();
2200             DoSplashSetScaleFactor(scale_factor);
2201             DoSplashLoadMemory(image_data, data_size);
2202             JLI_MemFree(image_data);
2203         }
2204     } else {
2205         DoSplashInit();
2206         if (isImageScaled) {
2207             DoSplashSetScaleFactor(scale_factor);
2208             DoSplashLoadFile(scaled_splash_name);
2209         } else {
2210             DoSplashLoadFile(file_name);
2211         }
2212     }
2213     JLI_MemFree(scaled_splash_name);
2214 
2215     DoSplashSetFileJarName(file_name, jar_name);
2216 
2217     /*
2218      * Done with all command line processing and potential re-execs so
2219      * clean up the environment.
2220      */
2221     (void)UnsetEnv(ENV_ENTRY);
2222     (void)UnsetEnv(SPLASH_FILE_ENV_ENTRY);
2223     (void)UnsetEnv(SPLASH_JAR_ENV_ENTRY);
2224 
2225     JLI_MemFree(splash_jar_entry);
2226     JLI_MemFree(splash_file_entry);
2227 
2228 }
2229 
2230 const char*
2231 GetFullVersion()
2232 {
2233     return _fVersion;
2234 }
2235 
2236 const char*
2237 GetProgramName()
2238 {
2239     return _program_name;
2240 }
2241 
2242 const char*
2243 GetLauncherName()
2244 {
2245     return _launcher_name;
2246 }
2247 
2248 jint
2249 GetErgoPolicy()
2250 {
2251     return _ergo_policy;
2252 }
2253 
2254 jboolean
2255 IsJavaArgs()
2256 {
2257     return _is_java_args;
2258 }
2259 
2260 static jboolean
2261 IsWildCardEnabled()
2262 {
2263     return _wc_enabled;
2264 }
2265 
2266 int
2267 ContinueInNewThread(InvocationFunctions* ifn, jlong threadStackSize,
2268                     int argc, char **argv,
2269                     int mode, char *what, int ret)
2270 {
2271 
2272     /*
2273      * If user doesn't specify stack size, check if VM has a preference.
2274      * Note that HotSpot no longer supports JNI_VERSION_1_1 but it will
2275      * return its default stack size through the init args structure.
2276      */
2277     if (threadStackSize == 0) {
2278       struct JDK1_1InitArgs args1_1;
2279       memset((void*)&args1_1, 0, sizeof(args1_1));
2280       args1_1.version = JNI_VERSION_1_1;
2281       ifn->GetDefaultJavaVMInitArgs(&args1_1);  /* ignore return value */
2282       if (args1_1.javaStackSize > 0) {
2283          threadStackSize = args1_1.javaStackSize;
2284       }
2285     }
2286 
2287     { /* Create a new thread to create JVM and invoke main method */
2288       JavaMainArgs args;
2289       int rslt;
2290 
2291       args.argc = argc;
2292       args.argv = argv;
2293       args.mode = mode;
2294       args.what = what;
2295       args.ifn = *ifn;
2296 
2297       rslt = ContinueInNewThread0(JavaMain, threadStackSize, (void*)&args);
2298       /* If the caller has deemed there is an error we
2299        * simply return that, otherwise we return the value of
2300        * the callee
2301        */
2302       return (ret != 0) ? ret : rslt;
2303     }
2304 }
2305 
2306 static void
2307 DumpState()
2308 {
2309     if (!JLI_IsTraceLauncher()) return ;
2310     printf("Launcher state:\n");
2311     printf("\tFirst application arg index: %d\n", JLI_GetAppArgIndex());
2312     printf("\tdebug:%s\n", (JLI_IsTraceLauncher() == JNI_TRUE) ? "on" : "off");
2313     printf("\tjavargs:%s\n", (_is_java_args == JNI_TRUE) ? "on" : "off");
2314     printf("\tprogram name:%s\n", GetProgramName());
2315     printf("\tlauncher name:%s\n", GetLauncherName());
2316     printf("\tjavaw:%s\n", (IsJavaw() == JNI_TRUE) ? "on" : "off");
2317     printf("\tfullversion:%s\n", GetFullVersion());
2318     printf("\tergo_policy:");
2319     switch(GetErgoPolicy()) {
2320         case NEVER_SERVER_CLASS:
2321             printf("NEVER_ACT_AS_A_SERVER_CLASS_MACHINE\n");
2322             break;
2323         case ALWAYS_SERVER_CLASS:
2324             printf("ALWAYS_ACT_AS_A_SERVER_CLASS_MACHINE\n");
2325             break;
2326         default:
2327             printf("DEFAULT_ERGONOMICS_POLICY\n");
2328     }
2329 }
2330 
2331 /*
2332  * Return JNI_TRUE for an option string that has no effect but should
2333  * _not_ be passed on to the vm; return JNI_FALSE otherwise.  On
2334  * Solaris SPARC, this screening needs to be done if:
2335  *    -d32 or -d64 is passed to a binary with an unmatched data model
2336  *    (the exec in CreateExecutionEnvironment removes -d<n> options and points the
2337  *    exec to the proper binary).  In the case of when the data model and the
2338  *    requested version is matched, an exec would not occur, and these options
2339  *    were erroneously passed to the vm.
2340  */
2341 jboolean
2342 RemovableOption(char * option)
2343 {
2344   /*
2345    * Unconditionally remove both -d32 and -d64 options since only
2346    * the last such options has an effect; e.g.
2347    * java -d32 -d64 -d32 -version
2348    * is equivalent to
2349    * java -d32 -version
2350    */
2351 
2352   if( (JLI_StrCCmp(option, "-d32")  == 0 ) ||
2353       (JLI_StrCCmp(option, "-d64")  == 0 ) )
2354     return JNI_TRUE;
2355   else
2356     return JNI_FALSE;
2357 }
2358 
2359 /*
2360  * A utility procedure to always print to stderr
2361  */
2362 void
2363 JLI_ReportMessage(const char* fmt, ...)
2364 {
2365     va_list vl;
2366     va_start(vl, fmt);
2367     vfprintf(stderr, fmt, vl);
2368     fprintf(stderr, "\n");
2369     va_end(vl);
2370 }