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