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