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     }
1347 
1348     if (*pwhat == NULL && --argc >= 0) {
1349         *pwhat = *argv++;
1350     }
1351 
1352     if (*pwhat == NULL) {
1353         /* LM_UNKNOWN okay for options that exit */
1354         if (!listModules && !describeModule && !validateModules && !dumpSharedSpaces) {
1355             *pret = 1;
1356         }
1357     } else if (mode == LM_UNKNOWN) {
1358         /* default to LM_CLASS if -m, -jar and -cp options are
1359          * not specified */
1360         if (!_have_classpath) {
1361             SetClassPath(".");
1362         }
1363         mode = IsSourceFile(arg) ? LM_SOURCE : LM_CLASS;
1364     } else if (mode == LM_CLASS && IsSourceFile(arg)) {
1365         /* override LM_CLASS mode if given a source file */
1366         mode = LM_SOURCE;
1367     }
1368 
1369     if (mode == LM_SOURCE) {
1370         AddOption("--add-modules=ALL-DEFAULT", NULL);
1371         *pwhat = SOURCE_LAUNCHER_MAIN_ENTRY;
1372         // adjust (argc, argv) so that the name of the source file
1373         // is included in the args passed to the source launcher
1374         // main entry class
1375         *pargc = argc + 1;
1376         *pargv = argv - 1;
1377     } else {
1378         if (argc >= 0) {
1379             *pargc = argc;
1380             *pargv = argv;
1381         }
1382     }
1383 
1384     *pmode = mode;
1385 
1386     if (!headless) {
1387         char *jar_path = NULL;
1388         if (mode == LM_JAR) {
1389             jar_path = *pwhat;
1390         }
1391         // Not in headless mode. We now set a couple of env variables that
1392         // will be used later by ShowSplashScreen().
1393         SetupSplashScreenEnvVars(splash_file_path, jar_path);
1394     }
1395 
1396     return JNI_TRUE;
1397 }
1398 
1399 /*
1400  * Sets the relevant environment variables that are subsequently used by
1401  * the ShowSplashScreen() function. The splash_file_path and jar_path parameters
1402  * are used to determine which environment variables to set.
1403  * The splash_file_path is the value that was provided to the "-splash:" option
1404  * when launching java. It may be null, which implies the "-splash:" option wasn't used.
1405  * The jar_path is the value that was provided to the "-jar" option when launching java.
1406  * It too may be null, which implies the "-jar" option wasn't used.
1407  */
1408 static void
1409 SetupSplashScreenEnvVars(const char *splash_file_path, char *jar_path) {
1410     // Command line specified "-splash:" takes priority over manifest one.
1411     if (splash_file_path) {
1412         // We set up the splash file name as a env variable which then gets
1413         // used when showing the splash screen in ShowSplashScreen().
1414 
1415         // create the string of the form _JAVA_SPLASH_FILE=<val>
1416         splash_file_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_FILE_ENV_ENTRY "=")
1417                                          + JLI_StrLen(splash_file_path) + 1);
1418         JLI_StrCpy(splash_file_entry, SPLASH_FILE_ENV_ENTRY "=");
1419         JLI_StrCat(splash_file_entry, splash_file_path);
1420         putenv(splash_file_entry);
1421         return;
1422     }
1423     if (!jar_path) {
1424         // no jar to look into for "SplashScreen-Image" manifest attribute
1425         return;
1426     }
1427     // parse the jar's manifest to find any "SplashScreen-Image"
1428     int res = 0;
1429     manifest_info  info;
1430     if ((res = JLI_ParseManifest(jar_path, &info)) != 0) {
1431         JLI_FreeManifest(); // cleanup any manifest structure
1432         if (res == -1) {
1433             JLI_ReportErrorMessage(JAR_ERROR2, jar_path);
1434         } else {
1435             JLI_ReportErrorMessage(JAR_ERROR3, jar_path);
1436         }
1437         exit(1);
1438     }
1439     if (!info.splashscreen_image_file_name) {
1440         JLI_FreeManifest(); // cleanup the manifest structure
1441         // no "SplashScreen-Image" in jar's manifest
1442         return;
1443     }
1444     // The jar's manifest had a "Splashscreen-Image" specified. We set up the jar entry name
1445     // and the jar file name as env variables which then get used when showing the splash screen
1446     // in ShowSplashScreen().
1447 
1448     // create the string of the form _JAVA_SPLASH_FILE=<val>
1449     splash_file_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_FILE_ENV_ENTRY "=")
1450                                      + JLI_StrLen(info.splashscreen_image_file_name) + 1);
1451     JLI_StrCpy(splash_file_entry, SPLASH_FILE_ENV_ENTRY "=");
1452     JLI_StrCat(splash_file_entry, info.splashscreen_image_file_name);
1453     putenv(splash_file_entry);
1454     // create the string of the form _JAVA_SPLASH_JAR=<val>
1455     splash_jar_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_JAR_ENV_ENTRY "=") + JLI_StrLen(jar_path) + 1);
1456     JLI_StrCpy(splash_jar_entry, SPLASH_JAR_ENV_ENTRY "=");
1457     JLI_StrCat(splash_jar_entry, jar_path);
1458     putenv(splash_jar_entry);
1459     JLI_FreeManifest(); // cleanup the manifest structure
1460 }
1461 
1462 /*
1463  * Initializes the Java Virtual Machine. Also frees options array when
1464  * finished.
1465  */
1466 static jboolean
1467 InitializeJVM(JavaVM **pvm, JNIEnv **penv, InvocationFunctions *ifn)
1468 {
1469     JavaVMInitArgs args;
1470     jint r;
1471 
1472     memset(&args, 0, sizeof(args));
1473     args.version  = JNI_VERSION_1_2;
1474     args.nOptions = numOptions;
1475     args.options  = options;
1476     args.ignoreUnrecognized = JNI_FALSE;
1477 
1478     if (JLI_IsTraceLauncher()) {
1479         int i = 0;
1480         printf("JavaVM args:\n    ");
1481         printf("version 0x%08lx, ", (long)args.version);
1482         printf("ignoreUnrecognized is %s, ",
1483                args.ignoreUnrecognized ? "JNI_TRUE" : "JNI_FALSE");
1484         printf("nOptions is %ld\n", (long)args.nOptions);
1485         for (i = 0; i < numOptions; i++)
1486             printf("    option[%2d] = '%s'\n",
1487                    i, args.options[i].optionString);
1488     }
1489 
1490     r = ifn->CreateJavaVM(pvm, (void **)penv, &args);
1491     JLI_MemFree(options);
1492     return r == JNI_OK;
1493 }
1494 
1495 static jclass helperClass = NULL;
1496 
1497 jclass
1498 GetLauncherHelperClass(JNIEnv *env)
1499 {
1500     if (helperClass == NULL) {
1501         NULL_CHECK0(helperClass = FindBootStrapClass(env,
1502                 "sun/launcher/LauncherHelper"));
1503     }
1504     return helperClass;
1505 }
1506 
1507 static jmethodID makePlatformStringMID = NULL;
1508 /*
1509  * Returns a new Java string object for the specified platform string.
1510  */
1511 static jstring
1512 NewPlatformString(JNIEnv *env, char *s)
1513 {
1514     int len = (int)JLI_StrLen(s);
1515     jbyteArray ary;
1516     jclass cls = GetLauncherHelperClass(env);
1517     NULL_CHECK0(cls);
1518     if (s == NULL)
1519         return 0;
1520 
1521     ary = (*env)->NewByteArray(env, len);
1522     if (ary != 0) {
1523         jstring str = 0;
1524         (*env)->SetByteArrayRegion(env, ary, 0, len, (jbyte *)s);
1525         if (!(*env)->ExceptionOccurred(env)) {
1526             if (makePlatformStringMID == NULL) {
1527                 NULL_CHECK0(makePlatformStringMID = (*env)->GetStaticMethodID(env,
1528                         cls, "makePlatformString", "(Z[B)Ljava/lang/String;"));
1529             }
1530             str = (*env)->CallStaticObjectMethod(env, cls,
1531                     makePlatformStringMID, USE_STDERR, ary);
1532             CHECK_EXCEPTION_RETURN_VALUE(0);
1533             (*env)->DeleteLocalRef(env, ary);
1534             return str;
1535         }
1536     }
1537     return 0;
1538 }
1539 
1540 /*
1541  * Returns a new array of Java string objects for the specified
1542  * array of platform strings.
1543  */
1544 jobjectArray
1545 NewPlatformStringArray(JNIEnv *env, char **strv, int strc)
1546 {
1547     jarray cls;
1548     jarray ary;
1549     int i;
1550 
1551     NULL_CHECK0(cls = FindBootStrapClass(env, "java/lang/String"));
1552     NULL_CHECK0(ary = (*env)->NewObjectArray(env, strc, cls, 0));
1553     CHECK_EXCEPTION_RETURN_VALUE(0);
1554     for (i = 0; i < strc; i++) {
1555         jstring str = NewPlatformString(env, *strv++);
1556         NULL_CHECK0(str);
1557         (*env)->SetObjectArrayElement(env, ary, i, str);
1558         (*env)->DeleteLocalRef(env, str);
1559     }
1560     return ary;
1561 }
1562 
1563 /*
1564  * Calls LauncherHelper::checkAndLoadMain to verify that the main class
1565  * is present, it is ok to load the main class and then load the main class.
1566  * For more details refer to the java implementation.
1567  */
1568 static jclass
1569 LoadMainClass(JNIEnv *env, int mode, char *name)
1570 {
1571     jmethodID mid;
1572     jstring str;
1573     jobject result;
1574     jlong start = 0, end = 0;
1575     jclass cls = GetLauncherHelperClass(env);
1576     NULL_CHECK0(cls);
1577     if (JLI_IsTraceLauncher()) {
1578         start = CurrentTimeMicros();
1579     }
1580     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1581                 "checkAndLoadMain",
1582                 "(ZILjava/lang/String;)Ljava/lang/Class;"));
1583 
1584     NULL_CHECK0(str = NewPlatformString(env, name));
1585     NULL_CHECK0(result = (*env)->CallStaticObjectMethod(env, cls, mid,
1586                                                         USE_STDERR, mode, str));
1587 
1588     if (JLI_IsTraceLauncher()) {
1589         end = CurrentTimeMicros();
1590         printf("%ld micro seconds to load main class\n", (long)(end-start));
1591         printf("----%s----\n", JLDEBUG_ENV_ENTRY);
1592     }
1593 
1594     return (jclass)result;
1595 }
1596 
1597 static jclass
1598 GetApplicationClass(JNIEnv *env)
1599 {
1600     jmethodID mid;
1601     jclass appClass;
1602     jclass cls = GetLauncherHelperClass(env);
1603     NULL_CHECK0(cls);
1604     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1605                 "getApplicationClass",
1606                 "()Ljava/lang/Class;"));
1607 
1608     appClass = (*env)->CallStaticObjectMethod(env, cls, mid);
1609     CHECK_EXCEPTION_RETURN_VALUE(0);
1610     return appClass;
1611 }
1612 
1613 static char* expandWildcardOnLongOpt(char* arg) {
1614     char *p, *value;
1615     size_t optLen, valueLen;
1616     p = JLI_StrChr(arg, '=');
1617 
1618     if (p == NULL || p[1] == '\0') {
1619         JLI_ReportErrorMessage(ARG_ERROR1, arg);
1620         exit(1);
1621     }
1622     p++;
1623     value = (char *) JLI_WildcardExpandClasspath(p);
1624     if (p == value) {
1625         // no wildcard
1626         return arg;
1627     }
1628 
1629     optLen = p - arg;
1630     valueLen = JLI_StrLen(value);
1631     p = JLI_MemAlloc(optLen + valueLen + 1);
1632     memcpy(p, arg, optLen);
1633     memcpy(p + optLen, value, valueLen);
1634     p[optLen + valueLen] = '\0';
1635     return p;
1636 }
1637 
1638 /*
1639  * For tools, convert command line args thus:
1640  *   javac -cp foo:foo/"*" -J-ms32m ...
1641  *   java -ms32m -cp JLI_WildcardExpandClasspath(foo:foo/"*") ...
1642  *
1643  * Takes 4 parameters, and returns the populated arguments
1644  */
1645 static void
1646 TranslateApplicationArgs(int jargc, const char **jargv, int *pargc, char ***pargv)
1647 {
1648     int argc = *pargc;
1649     char **argv = *pargv;
1650     int nargc = argc + jargc;
1651     char **nargv = JLI_MemAlloc((nargc + 1) * sizeof(char *));
1652     int i;
1653 
1654     *pargc = nargc;
1655     *pargv = nargv;
1656 
1657     /* Copy the VM arguments (i.e. prefixed with -J) */
1658     for (i = 0; i < jargc; i++) {
1659         const char *arg = jargv[i];
1660         if (arg[0] == '-' && arg[1] == 'J') {
1661             assert(arg[2] != '\0' && "Invalid JAVA_ARGS or EXTRA_JAVA_ARGS defined by build");
1662             *nargv++ = JLI_StringDup(arg + 2);
1663         }
1664     }
1665 
1666     for (i = 0; i < argc; i++) {
1667         char *arg = argv[i];
1668         if (arg[0] == '-' && arg[1] == 'J') {
1669             if (arg[2] == '\0') {
1670                 JLI_ReportErrorMessage(ARG_ERROR3);
1671                 exit(1);
1672             }
1673             *nargv++ = arg + 2;
1674         }
1675     }
1676 
1677     /* Copy the rest of the arguments */
1678     for (i = 0; i < jargc ; i++) {
1679         const char *arg = jargv[i];
1680         if (arg[0] != '-' || arg[1] != 'J') {
1681             *nargv++ = (arg == NULL) ? NULL : JLI_StringDup(arg);
1682         }
1683     }
1684     for (i = 0; i < argc; i++) {
1685         char *arg = argv[i];
1686         if (arg[0] == '-') {
1687             if (arg[1] == 'J')
1688                 continue;
1689             if (IsWildCardEnabled()) {
1690                 if (IsClassPathOption(arg) && i < argc - 1) {
1691                     *nargv++ = arg;
1692                     *nargv++ = (char *) JLI_WildcardExpandClasspath(argv[i+1]);
1693                     i++;
1694                     continue;
1695                 }
1696                 if (JLI_StrCCmp(arg, "--class-path=") == 0) {
1697                     *nargv++ = expandWildcardOnLongOpt(arg);
1698                     continue;
1699                 }
1700             }
1701         }
1702         *nargv++ = arg;
1703     }
1704     *nargv = 0;
1705 }
1706 
1707 /*
1708  * For our tools, we try to add 3 VM options:
1709  *      -Denv.class.path=<envcp>
1710  *      -Dapplication.home=<apphome>
1711  *      -Djava.class.path=<appcp>
1712  * <envcp>   is the user's setting of CLASSPATH -- for instance the user
1713  *           tells javac where to find binary classes through this environment
1714  *           variable.  Notice that users will be able to compile against our
1715  *           tools classes (sun.tools.javac.Main) only if they explicitly add
1716  *           tools.jar to CLASSPATH.
1717  * <apphome> is the directory where the application is installed.
1718  * <appcp>   is the classpath to where our apps' classfiles are.
1719  */
1720 static jboolean
1721 AddApplicationOptions(int cpathc, const char **cpathv)
1722 {
1723     char *envcp, *appcp, *apphome;
1724     char home[MAXPATHLEN]; /* application home */
1725     char separator[] = { PATH_SEPARATOR, '\0' };
1726     int size, i;
1727 
1728     {
1729         const char *s = getenv("CLASSPATH");
1730         if (s) {
1731             s = (char *) JLI_WildcardExpandClasspath(s);
1732             /* 40 for -Denv.class.path= */
1733             if (JLI_StrLen(s) + 40 > JLI_StrLen(s)) { // Safeguard from overflow
1734                 size_t envcpSize = JLI_StrLen(s) + 40;
1735                 envcp = (char *)JLI_MemAlloc(envcpSize);
1736                 snprintf(envcp, envcpSize, "-Denv.class.path=%s", s);
1737                 AddOption(envcp, NULL);
1738             }
1739         }
1740     }
1741 
1742     if (!GetApplicationHome(home, sizeof(home))) {
1743         JLI_ReportErrorMessage(CFG_ERROR5);
1744         return JNI_FALSE;
1745     }
1746 
1747     /* 40 for '-Dapplication.home=' */
1748     size_t apphomeSize = JLI_StrLen(home) + 40;
1749     apphome = (char *)JLI_MemAlloc(apphomeSize);
1750     snprintf(apphome, apphomeSize, "-Dapplication.home=%s", home);
1751     AddOption(apphome, NULL);
1752 
1753     /* How big is the application's classpath? */
1754     if (cpathc > 0) {
1755         size = 40;                                 /* 40: "-Djava.class.path=" */
1756         for (i = 0; i < cpathc; i++) {
1757             size += (int)JLI_StrLen(home) + (int)JLI_StrLen(cpathv[i]) + 1; /* 1: separator */
1758         }
1759         appcp = (char *)JLI_MemAlloc(size + 1);
1760         JLI_StrCpy(appcp, "-Djava.class.path=");
1761         for (i = 0; i < cpathc; i++) {
1762             JLI_StrCat(appcp, home);                        /* c:\program files\myapp */
1763             JLI_StrCat(appcp, cpathv[i]);           /* \lib\myapp.jar         */
1764             JLI_StrCat(appcp, separator);           /* ;                      */
1765         }
1766         appcp[JLI_StrLen(appcp)-1] = '\0';  /* remove trailing path separator */
1767         AddOption(appcp, NULL);
1768     }
1769     return JNI_TRUE;
1770 }
1771 
1772 /*
1773  * inject the -Dsun.java.command pseudo property into the args structure
1774  * this pseudo property is used in the HotSpot VM to expose the
1775  * Java class name and arguments to the main method to the VM. The
1776  * HotSpot VM uses this pseudo property to store the Java class name
1777  * (or jar file name) and the arguments to the class's main method
1778  * to the instrumentation memory region. The sun.java.command pseudo
1779  * property is not exported by HotSpot to the Java layer.
1780  */
1781 void
1782 SetJavaCommandLineProp(char *what, int argc, char **argv)
1783 {
1784 
1785     int i = 0;
1786     size_t len = 0;
1787     char* javaCommand = NULL;
1788     char* dashDstr = "-Dsun.java.command=";
1789 
1790     if (what == NULL) {
1791         /* unexpected, one of these should be set. just return without
1792          * setting the property
1793          */
1794         return;
1795     }
1796 
1797     /* determine the amount of memory to allocate assuming
1798      * the individual components will be space separated
1799      */
1800     len = JLI_StrLen(what);
1801     for (i = 0; i < argc; i++) {
1802         len += JLI_StrLen(argv[i]) + 1;
1803     }
1804 
1805     /* allocate the memory */
1806     javaCommand = (char*) JLI_MemAlloc(len + JLI_StrLen(dashDstr) + 1);
1807 
1808     /* build the -D string */
1809     *javaCommand = '\0';
1810     JLI_StrCat(javaCommand, dashDstr);
1811     JLI_StrCat(javaCommand, what);
1812 
1813     for (i = 0; i < argc; i++) {
1814         /* the components of the string are space separated. In
1815          * the case of embedded white space, the relationship of
1816          * the white space separated components to their true
1817          * positional arguments will be ambiguous. This issue may
1818          * be addressed in a future release.
1819          */
1820         JLI_StrCat(javaCommand, " ");
1821         JLI_StrCat(javaCommand, argv[i]);
1822     }
1823 
1824     AddOption(javaCommand, NULL);
1825 }
1826 
1827 /*
1828  * JVM would like to know if it's created by a standard Sun launcher, or by
1829  * user native application, the following property indicates the former.
1830  */
1831 static void SetJavaLauncherProp() {
1832   AddOption("-Dsun.java.launcher=SUN_STANDARD", NULL);
1833 }
1834 
1835 /*
1836  * Prints the version information from the java.version and other properties.
1837  */
1838 static void
1839 PrintJavaVersion(JNIEnv *env)
1840 {
1841     jclass ver;
1842     jmethodID print;
1843 
1844     NULL_CHECK(ver = FindBootStrapClass(env, "java/lang/VersionProps"));
1845     NULL_CHECK(print = (*env)->GetStaticMethodID(env,
1846                                                  ver,
1847                                                  "print",
1848                                                  "(Z)V"
1849                                                  )
1850               );
1851 
1852     (*env)->CallStaticVoidMethod(env, ver, print, printTo);
1853 }
1854 
1855 /*
1856  * Prints all the Java settings, see the java implementation for more details.
1857  */
1858 static void
1859 ShowSettings(JNIEnv *env, char *optString)
1860 {
1861     jmethodID showSettingsID;
1862     jstring joptString;
1863     jclass cls = GetLauncherHelperClass(env);
1864     NULL_CHECK(cls);
1865     NULL_CHECK(showSettingsID = (*env)->GetStaticMethodID(env, cls,
1866             "showSettings", "(ZLjava/lang/String;JJJ)V"));
1867     NULL_CHECK(joptString = (*env)->NewStringUTF(env, optString));
1868     (*env)->CallStaticVoidMethod(env, cls, showSettingsID,
1869                                  USE_STDERR,
1870                                  joptString,
1871                                  (jlong)initialHeapSize,
1872                                  (jlong)maxHeapSize,
1873                                  (jlong)threadStackSize);
1874 }
1875 
1876 /**
1877  * Show resolved modules
1878  */
1879 static void
1880 ShowResolvedModules(JNIEnv *env)
1881 {
1882     jmethodID showResolvedModulesID;
1883     jclass cls = GetLauncherHelperClass(env);
1884     NULL_CHECK(cls);
1885     NULL_CHECK(showResolvedModulesID = (*env)->GetStaticMethodID(env, cls,
1886             "showResolvedModules", "()V"));
1887     (*env)->CallStaticVoidMethod(env, cls, showResolvedModulesID);
1888 }
1889 
1890 /**
1891  * List observable modules
1892  */
1893 static void
1894 ListModules(JNIEnv *env)
1895 {
1896     jmethodID listModulesID;
1897     jclass cls = GetLauncherHelperClass(env);
1898     NULL_CHECK(cls);
1899     NULL_CHECK(listModulesID = (*env)->GetStaticMethodID(env, cls,
1900             "listModules", "()V"));
1901     (*env)->CallStaticVoidMethod(env, cls, listModulesID);
1902 }
1903 
1904 /**
1905  * Describe a module
1906  */
1907 static void
1908 DescribeModule(JNIEnv *env, char *optString)
1909 {
1910     jmethodID describeModuleID;
1911     jstring joptString = NULL;
1912     jclass cls = GetLauncherHelperClass(env);
1913     NULL_CHECK(cls);
1914     NULL_CHECK(describeModuleID = (*env)->GetStaticMethodID(env, cls,
1915             "describeModule", "(Ljava/lang/String;)V"));
1916     NULL_CHECK(joptString = NewPlatformString(env, optString));
1917     (*env)->CallStaticVoidMethod(env, cls, describeModuleID, joptString);
1918 }
1919 
1920 /*
1921  * Prints default usage or the Xusage message, see sun.launcher.LauncherHelper.java
1922  */
1923 static void
1924 PrintUsage(JNIEnv* env, jboolean doXUsage)
1925 {
1926   jmethodID initHelp, vmSelect, vmSynonym, printHelp, printXUsageMessage;
1927   jstring jprogname, vm1, vm2;
1928   int i;
1929   jclass cls = GetLauncherHelperClass(env);
1930   NULL_CHECK(cls);
1931   if (doXUsage) {
1932     NULL_CHECK(printXUsageMessage = (*env)->GetStaticMethodID(env, cls,
1933                                         "printXUsageMessage", "(Z)V"));
1934     (*env)->CallStaticVoidMethod(env, cls, printXUsageMessage, printTo);
1935   } else {
1936     NULL_CHECK(initHelp = (*env)->GetStaticMethodID(env, cls,
1937                                         "initHelpMessage", "(Ljava/lang/String;)V"));
1938 
1939     NULL_CHECK(vmSelect = (*env)->GetStaticMethodID(env, cls, "appendVmSelectMessage",
1940                                         "(Ljava/lang/String;Ljava/lang/String;)V"));
1941 
1942     NULL_CHECK(vmSynonym = (*env)->GetStaticMethodID(env, cls,
1943                                         "appendVmSynonymMessage",
1944                                         "(Ljava/lang/String;Ljava/lang/String;)V"));
1945 
1946     NULL_CHECK(printHelp = (*env)->GetStaticMethodID(env, cls,
1947                                         "printHelpMessage", "(Z)V"));
1948 
1949     NULL_CHECK(jprogname = (*env)->NewStringUTF(env, _program_name));
1950 
1951     /* Initialize the usage message with the usual preamble */
1952     (*env)->CallStaticVoidMethod(env, cls, initHelp, jprogname);
1953     CHECK_EXCEPTION_RETURN();
1954 
1955 
1956     /* Assemble the other variant part of the usage */
1957     for (i=1; i<knownVMsCount; i++) {
1958       if (knownVMs[i].flag == VM_KNOWN) {
1959         NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
1960         NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].name+1));
1961         (*env)->CallStaticVoidMethod(env, cls, vmSelect, vm1, vm2);
1962         CHECK_EXCEPTION_RETURN();
1963       }
1964     }
1965     for (i=1; i<knownVMsCount; i++) {
1966       if (knownVMs[i].flag == VM_ALIASED_TO) {
1967         NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
1968         NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].alias+1));
1969         (*env)->CallStaticVoidMethod(env, cls, vmSynonym, vm1, vm2);
1970         CHECK_EXCEPTION_RETURN();
1971       }
1972     }
1973 
1974     /* Complete the usage message and print to stderr*/
1975     (*env)->CallStaticVoidMethod(env, cls, printHelp, printTo);
1976   }
1977   return;
1978 }
1979 
1980 /*
1981  * Read the jvm.cfg file and fill the knownJVMs[] array.
1982  *
1983  * The functionality of the jvm.cfg file is subject to change without
1984  * notice and the mechanism will be removed in the future.
1985  *
1986  * The lexical structure of the jvm.cfg file is as follows:
1987  *
1988  *     jvmcfg         :=  { vmLine }
1989  *     vmLine         :=  knownLine
1990  *                    |   aliasLine
1991  *                    |   warnLine
1992  *                    |   ignoreLine
1993  *                    |   errorLine
1994  *                    |   predicateLine
1995  *                    |   commentLine
1996  *     knownLine      :=  flag  "KNOWN"                  EOL
1997  *     warnLine       :=  flag  "WARN"                   EOL
1998  *     ignoreLine     :=  flag  "IGNORE"                 EOL
1999  *     errorLine      :=  flag  "ERROR"                  EOL
2000  *     aliasLine      :=  flag  "ALIASED_TO"       flag  EOL
2001  *     predicateLine  :=  flag  "IF_SERVER_CLASS"  flag  EOL
2002  *     commentLine    :=  "#" text                       EOL
2003  *     flag           :=  "-" identifier
2004  *
2005  * The semantics are that when someone specifies a flag on the command line:
2006  * - if the flag appears on a knownLine, then the identifier is used as
2007  *   the name of the directory holding the JVM library (the name of the JVM).
2008  * - if the flag appears as the first flag on an aliasLine, the identifier
2009  *   of the second flag is used as the name of the JVM.
2010  * - if the flag appears on a warnLine, the identifier is used as the
2011  *   name of the JVM, but a warning is generated.
2012  * - if the flag appears on an ignoreLine, the identifier is recognized as the
2013  *   name of a JVM, but the identifier is ignored and the default vm used
2014  * - if the flag appears on an errorLine, an error is generated.
2015  * - if the flag appears as the first flag on a predicateLine, and
2016  *   the machine on which you are running passes the predicate indicated,
2017  *   then the identifier of the second flag is used as the name of the JVM,
2018  *   otherwise the identifier of the first flag is used as the name of the JVM.
2019  * If no flag is given on the command line, the first vmLine of the jvm.cfg
2020  * file determines the name of the JVM.
2021  * PredicateLines are only interpreted on first vmLine of a jvm.cfg file,
2022  * since they only make sense if someone hasn't specified the name of the
2023  * JVM on the command line.
2024  *
2025  * The intent of the jvm.cfg file is to allow several JVM libraries to
2026  * be installed in different subdirectories of a single JRE installation,
2027  * for space-savings and convenience in testing.
2028  * The intent is explicitly not to provide a full aliasing or predicate
2029  * mechanism.
2030  */
2031 jint
2032 ReadKnownVMs(const char *jvmCfgName, jboolean speculative)
2033 {
2034     FILE *jvmCfg;
2035     char line[MAXPATHLEN+20];
2036     int cnt = 0;
2037     int lineno = 0;
2038     jlong start = 0, end = 0;
2039     int vmType;
2040     char *tmpPtr;
2041     char *altVMName = NULL;
2042     static char *whiteSpace = " \t";
2043     if (JLI_IsTraceLauncher()) {
2044         start = CurrentTimeMicros();
2045     }
2046 
2047     jvmCfg = fopen(jvmCfgName, "r");
2048     if (jvmCfg == NULL) {
2049       if (!speculative) {
2050         JLI_ReportErrorMessage(CFG_ERROR6, jvmCfgName);
2051         exit(1);
2052       } else {
2053         return -1;
2054       }
2055     }
2056     while (fgets(line, sizeof(line), jvmCfg) != NULL) {
2057         vmType = VM_UNKNOWN;
2058         lineno++;
2059         if (line[0] == '#')
2060             continue;
2061         if (line[0] != '-') {
2062             JLI_ReportErrorMessage(CFG_WARN2, lineno, jvmCfgName);
2063         }
2064         if (cnt >= knownVMsLimit) {
2065             GrowKnownVMs(cnt);
2066         }
2067         line[JLI_StrLen(line)-1] = '\0'; /* remove trailing newline */
2068         tmpPtr = line + JLI_StrCSpn(line, whiteSpace);
2069         if (*tmpPtr == 0) {
2070             JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2071         } else {
2072             /* Null-terminate this string for JLI_StringDup below */
2073             *tmpPtr++ = 0;
2074             tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
2075             if (*tmpPtr == 0) {
2076                 JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2077             } else {
2078                 if (!JLI_StrCCmp(tmpPtr, "KNOWN")) {
2079                     vmType = VM_KNOWN;
2080                 } else if (!JLI_StrCCmp(tmpPtr, "ALIASED_TO")) {
2081                     tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
2082                     if (*tmpPtr != 0) {
2083                         tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
2084                     }
2085                     if (*tmpPtr == 0) {
2086                         JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2087                     } else {
2088                         /* Null terminate altVMName */
2089                         altVMName = tmpPtr;
2090                         tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
2091                         *tmpPtr = 0;
2092                         vmType = VM_ALIASED_TO;
2093                     }
2094                 } else if (!JLI_StrCCmp(tmpPtr, "WARN")) {
2095                     vmType = VM_WARN;
2096                 } else if (!JLI_StrCCmp(tmpPtr, "IGNORE")) {
2097                     vmType = VM_IGNORE;
2098                 } else if (!JLI_StrCCmp(tmpPtr, "ERROR")) {
2099                     vmType = VM_ERROR;
2100                 } else if (!JLI_StrCCmp(tmpPtr, "IF_SERVER_CLASS")) {
2101                     /* ignored */
2102                 } else {
2103                     JLI_ReportErrorMessage(CFG_WARN5, lineno, &jvmCfgName[0]);
2104                     vmType = VM_KNOWN;
2105                 }
2106             }
2107         }
2108 
2109         JLI_TraceLauncher("jvm.cfg[%d] = ->%s<-\n", cnt, line);
2110         if (vmType != VM_UNKNOWN) {
2111             knownVMs[cnt].name = JLI_StringDup(line);
2112             knownVMs[cnt].flag = vmType;
2113             switch (vmType) {
2114             default:
2115                 break;
2116             case VM_ALIASED_TO:
2117                 knownVMs[cnt].alias = JLI_StringDup(altVMName);
2118                 JLI_TraceLauncher("    name: %s  vmType: %s  alias: %s\n",
2119                    knownVMs[cnt].name, "VM_ALIASED_TO", knownVMs[cnt].alias);
2120                 break;
2121             }
2122             cnt++;
2123         }
2124     }
2125     fclose(jvmCfg);
2126     knownVMsCount = cnt;
2127 
2128     if (JLI_IsTraceLauncher()) {
2129         end = CurrentTimeMicros();
2130         printf("%ld micro seconds to parse jvm.cfg\n", (long)(end-start));
2131     }
2132 
2133     return cnt;
2134 }
2135 
2136 
2137 static void
2138 GrowKnownVMs(int minimum)
2139 {
2140     struct vmdesc* newKnownVMs;
2141     int newMax;
2142 
2143     newMax = (knownVMsLimit == 0 ? INIT_MAX_KNOWN_VMS : (2 * knownVMsLimit));
2144     if (newMax <= minimum) {
2145         newMax = minimum;
2146     }
2147     newKnownVMs = (struct vmdesc*) JLI_MemAlloc(newMax * sizeof(struct vmdesc));
2148     if (knownVMs != NULL) {
2149         memcpy(newKnownVMs, knownVMs, knownVMsLimit * sizeof(struct vmdesc));
2150     }
2151     JLI_MemFree(knownVMs);
2152     knownVMs = newKnownVMs;
2153     knownVMsLimit = newMax;
2154 }
2155 
2156 
2157 /* Returns index of VM or -1 if not found */
2158 static int
2159 KnownVMIndex(const char* name)
2160 {
2161     int i;
2162     if (JLI_StrCCmp(name, "-J") == 0) name += 2;
2163     for (i = 0; i < knownVMsCount; i++) {
2164         if (!JLI_StrCmp(name, knownVMs[i].name)) {
2165             return i;
2166         }
2167     }
2168     return -1;
2169 }
2170 
2171 static void
2172 FreeKnownVMs()
2173 {
2174     int i;
2175     for (i = 0; i < knownVMsCount; i++) {
2176         JLI_MemFree(knownVMs[i].name);
2177         knownVMs[i].name = NULL;
2178     }
2179     JLI_MemFree(knownVMs);
2180 }
2181 
2182 /*
2183  * Displays the splash screen according to the jar file name
2184  * and image file names stored in environment variables
2185  */
2186 void
2187 ShowSplashScreen()
2188 {
2189     const char *jar_name = getenv(SPLASH_JAR_ENV_ENTRY);
2190     const char *file_name = getenv(SPLASH_FILE_ENV_ENTRY);
2191     int data_size;
2192     void *image_data = NULL;
2193     float scale_factor = 1;
2194     char *scaled_splash_name = NULL;
2195     jboolean isImageScaled = JNI_FALSE;
2196     size_t maxScaledImgNameLength = 0;
2197     if (file_name == NULL){
2198         return;
2199     }
2200 
2201     if (!DoSplashInit()) {
2202         goto exit;
2203     }
2204 
2205     maxScaledImgNameLength = DoSplashGetScaledImgNameMaxPstfixLen(file_name);
2206 
2207     scaled_splash_name = JLI_MemAlloc(
2208                             maxScaledImgNameLength * sizeof(char));
2209     isImageScaled = DoSplashGetScaledImageName(jar_name, file_name,
2210                             &scale_factor,
2211                             scaled_splash_name, maxScaledImgNameLength);
2212     if (jar_name) {
2213 
2214         if (isImageScaled) {
2215             image_data = JLI_JarUnpackFile(
2216                     jar_name, scaled_splash_name, &data_size);
2217         }
2218 
2219         if (!image_data) {
2220             scale_factor = 1;
2221             image_data = JLI_JarUnpackFile(
2222                             jar_name, file_name, &data_size);
2223         }
2224         if (image_data) {
2225             DoSplashSetScaleFactor(scale_factor);
2226             DoSplashLoadMemory(image_data, data_size);
2227             JLI_MemFree(image_data);
2228         } else {
2229             DoSplashClose();
2230         }
2231     } else {
2232         if (isImageScaled) {
2233             DoSplashSetScaleFactor(scale_factor);
2234             DoSplashLoadFile(scaled_splash_name);
2235         } else {
2236             DoSplashLoadFile(file_name);
2237         }
2238     }
2239     JLI_MemFree(scaled_splash_name);
2240 
2241     DoSplashSetFileJarName(file_name, jar_name);
2242 
2243     exit:
2244     /*
2245      * Done with all command line processing and potential re-execs so
2246      * clean up the environment.
2247      */
2248     (void)UnsetEnv(MAIN_CLASS_ENV_ENTRY);
2249     (void)UnsetEnv(SPLASH_FILE_ENV_ENTRY);
2250     (void)UnsetEnv(SPLASH_JAR_ENV_ENTRY);
2251 
2252     JLI_MemFree(splash_jar_entry);
2253     JLI_MemFree(splash_file_entry);
2254 
2255 }
2256 
2257 static const char* GetFullVersion()
2258 {
2259     return _fVersion;
2260 }
2261 
2262 static const char* GetProgramName()
2263 {
2264     return _program_name;
2265 }
2266 
2267 static const char* GetLauncherName()
2268 {
2269     return _launcher_name;
2270 }
2271 
2272 static jboolean IsJavaArgs()
2273 {
2274     return _is_java_args;
2275 }
2276 
2277 static jboolean
2278 IsWildCardEnabled()
2279 {
2280     return _wc_enabled;
2281 }
2282 
2283 int
2284 ContinueInNewThread(InvocationFunctions* ifn, jlong threadStackSize,
2285                     int argc, char **argv,
2286                     int mode, char *what, int ret)
2287 {
2288     if (threadStackSize == 0) {
2289         /*
2290          * If the user hasn't specified a non-zero stack size ask the JVM for its default.
2291          * A returned 0 means 'use the system default' for a platform, e.g., Windows.
2292          * Note that HotSpot no longer supports JNI_VERSION_1_1 but it will
2293          * return its default stack size through the init args structure.
2294          */
2295         struct JDK1_1InitArgs args1_1;
2296         memset((void*)&args1_1, 0, sizeof(args1_1));
2297         args1_1.version = JNI_VERSION_1_1;
2298         ifn->GetDefaultJavaVMInitArgs(&args1_1);  /* ignore return value */
2299         if (args1_1.javaStackSize > 0) {
2300             threadStackSize = args1_1.javaStackSize;
2301         }
2302     }
2303 
2304     { /* Create a new thread to create JVM and invoke main method */
2305         JavaMainArgs args;
2306         int rslt;
2307 
2308         args.argc = argc;
2309         args.argv = argv;
2310         args.mode = mode;
2311         args.what = what;
2312         args.ifn = *ifn;
2313 
2314         rslt = CallJavaMainInNewThread(threadStackSize, (void*)&args);
2315         /* If the caller has deemed there is an error we
2316          * simply return that, otherwise we return the value of
2317          * the callee
2318          */
2319         return (ret != 0) ? ret : rslt;
2320     }
2321 }
2322 
2323 static void
2324 DumpState()
2325 {
2326     if (!JLI_IsTraceLauncher()) return ;
2327     printf("Launcher state:\n");
2328     printf("\tFirst application arg index: %d\n", JLI_GetAppArgIndex());
2329     printf("\tdebug:%s\n", (JLI_IsTraceLauncher() == JNI_TRUE) ? "on" : "off");
2330     printf("\tjavargs:%s\n", (_is_java_args == JNI_TRUE) ? "on" : "off");
2331     printf("\tprogram name:%s\n", GetProgramName());
2332     printf("\tlauncher name:%s\n", GetLauncherName());
2333     printf("\tjavaw:%s\n", (IsJavaw() == JNI_TRUE) ? "on" : "off");
2334     printf("\tfullversion:%s\n", GetFullVersion());
2335 }
2336 
2337 /*
2338  * A utility procedure to always print to stderr
2339  */
2340 JNIEXPORT void JNICALL
2341 JLI_ReportMessage(const char* fmt, ...)
2342 {
2343     va_list vl;
2344     va_start(vl, fmt);
2345     vfprintf(stderr, fmt, vl);
2346     fprintf(stderr, "\n");
2347     va_end(vl);
2348 }
2349 
2350 /*
2351  * A utility procedure to always print to stdout
2352  */
2353 void
2354 JLI_ShowMessage(const char* fmt, ...)
2355 {
2356     va_list vl;
2357     va_start(vl, fmt);
2358     vfprintf(stdout, fmt, vl);
2359     fprintf(stdout, "\n");
2360     va_end(vl);
2361 }