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