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