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