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 }
 670 
 671 /*
 672  * Test if the given name is one of the class path options.
 673  */
 674 static jboolean
 675 IsClassPathOption(const char* name) {
 676     return JLI_StrCmp(name, "-classpath") == 0 ||
 677            JLI_StrCmp(name, "-cp") == 0 ||
 678            JLI_StrCmp(name, "--class-path") == 0;
 679 }
 680 
 681 /*
 682  * Test if the given name is a launcher option taking the main entry point.
 683  */
 684 static jboolean
 685 IsLauncherMainOption(const char* name) {
 686     return JLI_StrCmp(name, "--module") == 0 ||
 687            JLI_StrCmp(name, "-m") == 0;
 688 }
 689 
 690 /*
 691  * Test if the given name is a white-space launcher option.
 692  */
 693 static jboolean
 694 IsLauncherOption(const char* name) {
 695     return IsClassPathOption(name) ||
 696            IsLauncherMainOption(name) ||
 697            JLI_StrCmp(name, "--describe-module") == 0 ||
 698            JLI_StrCmp(name, "-d") == 0 ||
 699            JLI_StrCmp(name, "--source") == 0;
 700 }
 701 
 702 /*
 703  * Test if the given name is a module-system white-space option that
 704  * will be passed to the VM with its corresponding long-form option
 705  * name and "=" delimiter.
 706  */
 707 static jboolean
 708 IsModuleOption(const char* name) {
 709     return JLI_StrCmp(name, "--module-path") == 0 ||
 710            JLI_StrCmp(name, "-p") == 0 ||
 711            JLI_StrCmp(name, "--upgrade-module-path") == 0 ||
 712            JLI_StrCmp(name, "--add-modules") == 0 ||
 713            JLI_StrCmp(name, "--enable-native-access") == 0 ||
 714            JLI_StrCmp(name, "--limit-modules") == 0 ||
 715            JLI_StrCmp(name, "--add-exports") == 0 ||
 716            JLI_StrCmp(name, "--add-opens") == 0 ||
 717            JLI_StrCmp(name, "--add-reads") == 0 ||
 718            JLI_StrCmp(name, "--patch-module") == 0;
 719 }
 720 
 721 static jboolean
 722 IsLongFormModuleOption(const char* name) {
 723     return JLI_StrCCmp(name, "--module-path=") == 0 ||
 724            JLI_StrCCmp(name, "--upgrade-module-path=") == 0 ||
 725            JLI_StrCCmp(name, "--add-modules=") == 0 ||
 726            JLI_StrCCmp(name, "--enable-native-access=") == 0 ||
 727            JLI_StrCCmp(name, "--limit-modules=") == 0 ||
 728            JLI_StrCCmp(name, "--add-exports=") == 0 ||
 729            JLI_StrCCmp(name, "--add-reads=") == 0 ||
 730            JLI_StrCCmp(name, "--patch-module=") == 0;
 731 }
 732 
 733 /*
 734  * Test if the given name has a white space option.
 735  */
 736 jboolean
 737 IsWhiteSpaceOption(const char* name) {
 738     return IsModuleOption(name) ||
 739            IsLauncherOption(name);
 740 }
 741 
 742 /*
 743  * Check if it is OK to set the mode.
 744  * If the mode was previously set, and should not be changed,
 745  * a fatal error is reported.
 746  */
 747 static int
 748 checkMode(int mode, int newMode, const char *arg) {
 749     if (mode == LM_SOURCE) {
 750         JLI_ReportErrorMessage(ARG_ERROR14, arg);
 751         exit(1);
 752     }
 753     return newMode;
 754 }
 755 
 756 /*
 757  * Test if an arg identifies a source file.
 758  */
 759 static jboolean IsSourceFile(const char *arg) {
 760     struct stat st;
 761     return (JLI_HasSuffix(arg, ".java") && stat(arg, &st) == 0);
 762 }
 763 
 764 /*
 765  * Checks the command line options to find which JVM type was
 766  * specified.  If no command line option was given for the JVM type,
 767  * the default type is used.  The environment variable
 768  * JDK_ALTERNATE_VM and the command line option -XXaltjvm= are also
 769  * checked as ways of specifying which JVM type to invoke.
 770  */
 771 char *
 772 CheckJvmType(int *pargc, char ***argv, jboolean speculative) {
 773     int i, argi;
 774     int argc;
 775     char **newArgv;
 776     int newArgvIdx = 0;
 777     int isVMType;
 778     int jvmidx = -1;
 779     char *jvmtype = getenv("JDK_ALTERNATE_VM");
 780 
 781     argc = *pargc;
 782 
 783     /* To make things simpler we always copy the argv array */
 784     newArgv = JLI_MemAlloc((argc + 1) * sizeof(char *));
 785 
 786     /* The program name is always present */
 787     newArgv[newArgvIdx++] = (*argv)[0];
 788 
 789     for (argi = 1; argi < argc; argi++) {
 790         char *arg = (*argv)[argi];
 791         isVMType = 0;
 792 
 793         if (IsJavaArgs()) {
 794             if (arg[0] != '-') {
 795                 newArgv[newArgvIdx++] = arg;
 796                 continue;
 797             }
 798         } else {
 799             if (IsWhiteSpaceOption(arg)) {
 800                 newArgv[newArgvIdx++] = arg;
 801                 argi++;
 802                 if (argi < argc) {
 803                     newArgv[newArgvIdx++] = (*argv)[argi];
 804                 }
 805                 continue;
 806             }
 807             if (arg[0] != '-') break;
 808         }
 809 
 810         /* Did the user pass an explicit VM type? */
 811         i = KnownVMIndex(arg);
 812         if (i >= 0) {
 813             jvmtype = knownVMs[jvmidx = i].name + 1; /* skip the - */
 814             isVMType = 1;
 815             *pargc = *pargc - 1;
 816         }
 817 
 818         /* Did the user specify an "alternate" VM? */
 819         else if (JLI_StrCCmp(arg, "-XXaltjvm=") == 0 || JLI_StrCCmp(arg, "-J-XXaltjvm=") == 0) {
 820             isVMType = 1;
 821             jvmtype = arg+((arg[1]=='X')? 10 : 12);
 822             jvmidx = -1;
 823         }
 824 
 825         if (!isVMType) {
 826             newArgv[newArgvIdx++] = arg;
 827         }
 828     }
 829 
 830     /*
 831      * Finish copying the arguments if we aborted the above loop.
 832      * NOTE that if we aborted via "break" then we did NOT copy the
 833      * last argument above, and in addition argi will be less than
 834      * argc.
 835      */
 836     while (argi < argc) {
 837         newArgv[newArgvIdx++] = (*argv)[argi];
 838         argi++;
 839     }
 840 
 841     /* argv is null-terminated */
 842     newArgv[newArgvIdx] = 0;
 843 
 844     /* Copy back argv */
 845     *argv = newArgv;
 846     *pargc = newArgvIdx;
 847 
 848     /* use the default VM type if not specified (no alias processing) */
 849     if (jvmtype == NULL) {
 850       char* result = knownVMs[0].name+1;
 851       JLI_TraceLauncher("Default VM: %s\n", result);
 852       return result;
 853     }
 854 
 855     /* if using an alternate VM, no alias processing */
 856     if (jvmidx < 0)
 857       return jvmtype;
 858 
 859     /* Resolve aliases first */
 860     {
 861       int loopCount = 0;
 862       while (knownVMs[jvmidx].flag == VM_ALIASED_TO) {
 863         int nextIdx = KnownVMIndex(knownVMs[jvmidx].alias);
 864 
 865         if (loopCount > knownVMsCount) {
 866           if (!speculative) {
 867             JLI_ReportErrorMessage(CFG_ERROR1);
 868             exit(1);
 869           } else {
 870             return "ERROR";
 871             /* break; */
 872           }
 873         }
 874 
 875         if (nextIdx < 0) {
 876           if (!speculative) {
 877             JLI_ReportErrorMessage(CFG_ERROR2, knownVMs[jvmidx].alias);
 878             exit(1);
 879           } else {
 880             return "ERROR";
 881           }
 882         }
 883         jvmidx = nextIdx;
 884         jvmtype = knownVMs[jvmidx].name+1;
 885         loopCount++;
 886       }
 887     }
 888 
 889     switch (knownVMs[jvmidx].flag) {
 890     case VM_WARN:
 891         if (!speculative) {
 892             JLI_ReportErrorMessage(CFG_WARN1, jvmtype, knownVMs[0].name + 1);
 893         }
 894         /* fall through */
 895     case VM_IGNORE:
 896         jvmtype = knownVMs[jvmidx=0].name + 1;
 897         /* fall through */
 898     case VM_KNOWN:
 899         break;
 900     case VM_ERROR:
 901         if (!speculative) {
 902             JLI_ReportErrorMessage(CFG_ERROR3, jvmtype);
 903             exit(1);
 904         } else {
 905             return "ERROR";
 906         }
 907     }
 908 
 909     return jvmtype;
 910 }
 911 
 912 /* copied from HotSpot function "atomll()" */
 913 static int
 914 parse_size(const char *s, jlong *result) {
 915   jlong n = 0;
 916   int args_read = sscanf(s, JLONG_FORMAT_SPECIFIER, &n);
 917   if (args_read != 1) {
 918     return 0;
 919   }
 920   while (*s != '\0' && *s >= '0' && *s <= '9') {
 921     s++;
 922   }
 923   // 4705540: illegal if more characters are found after the first non-digit
 924   if (JLI_StrLen(s) > 1) {
 925     return 0;
 926   }
 927   switch (*s) {
 928     case 'T': case 't':
 929       *result = n * GB * KB;
 930       return 1;
 931     case 'G': case 'g':
 932       *result = n * GB;
 933       return 1;
 934     case 'M': case 'm':
 935       *result = n * MB;
 936       return 1;
 937     case 'K': case 'k':
 938       *result = n * KB;
 939       return 1;
 940     case '\0':
 941       *result = n;
 942       return 1;
 943     default:
 944       /* Create JVM with default stack and let VM handle malformed -Xss string*/
 945       return 0;
 946   }
 947 }
 948 
 949 /*
 950  * Adds a new VM option with the given name and value.
 951  */
 952 void
 953 AddOption(char *str, void *info)
 954 {
 955     /*
 956      * Expand options array if needed to accommodate at least one more
 957      * VM option.
 958      */
 959     if (numOptions >= maxOptions) {
 960         if (options == 0) {
 961             maxOptions = 4;
 962             options = JLI_MemAlloc(maxOptions * sizeof(JavaVMOption));
 963         } else {
 964             JavaVMOption *tmp;
 965             maxOptions *= 2;
 966             tmp = JLI_MemAlloc(maxOptions * sizeof(JavaVMOption));
 967             memcpy(tmp, options, numOptions * sizeof(JavaVMOption));
 968             JLI_MemFree(options);
 969             options = tmp;
 970         }
 971     }
 972     options[numOptions].optionString = str;
 973     options[numOptions++].extraInfo = info;
 974 
 975     /*
 976      * -Xss is used both by the JVM and here to establish the stack size of the thread
 977      * created to launch the JVM. In the latter case we need to ensure we don't go
 978      * below the minimum stack size allowed. If -Xss is zero that tells the JVM to use
 979      * 'default' sizes (either from JVM or system configuration, e.g. 'ulimit -s' on linux),
 980      * and is not itself a small stack size that will be rejected. So we ignore -Xss0 here.
 981      */
 982     if (JLI_StrCCmp(str, "-Xss") == 0) {
 983         jlong tmp;
 984         if (parse_size(str + 4, &tmp)) {
 985             threadStackSize = tmp;
 986             if (threadStackSize > 0 && threadStackSize < (jlong)STACK_SIZE_MINIMUM) {
 987                 threadStackSize = STACK_SIZE_MINIMUM;
 988             }
 989         }
 990     }
 991 
 992     if (JLI_StrCCmp(str, "-Xmx") == 0) {
 993         jlong tmp;
 994         if (parse_size(str + 4, &tmp)) {
 995             maxHeapSize = tmp;
 996         }
 997     }
 998 
 999     if (JLI_StrCCmp(str, "-Xms") == 0) {
1000         jlong tmp;
1001         if (parse_size(str + 4, &tmp)) {
1002            initialHeapSize = tmp;
1003         }
1004     }
1005 }
1006 
1007 static void
1008 SetClassPath(const char *s)
1009 {
1010     char *def;
1011     const char *orig = s;
1012     static const char format[] = "-Djava.class.path=%s";
1013     /*
1014      * usually we should not get a null pointer, but there are cases where
1015      * we might just get one, in which case we simply ignore it, and let the
1016      * caller deal with it
1017      */
1018     if (s == NULL)
1019         return;
1020     s = JLI_WildcardExpandClasspath(s);
1021     if (s == NULL)
1022         return;
1023     if (sizeof(format) - 2 + JLI_StrLen(s) < JLI_StrLen(s))
1024         // s is became corrupted after expanding wildcards
1025         return;
1026     size_t defSize = sizeof(format)
1027                        - 2 /* strlen("%s") */
1028                        + JLI_StrLen(s);
1029     def = JLI_MemAlloc(defSize);
1030     snprintf(def, defSize, format, s);
1031     AddOption(def, NULL);
1032     if (s != orig)
1033         JLI_MemFree((char *) s);
1034     _have_classpath = JNI_TRUE;
1035 }
1036 
1037 static void
1038 AddLongFormOption(const char *option, const char *arg)
1039 {
1040     static const char format[] = "%s=%s";
1041     char *def;
1042     size_t def_len;
1043 
1044     def_len = JLI_StrLen(option) + 1 + JLI_StrLen(arg) + 1;
1045     def = JLI_MemAlloc(def_len);
1046     JLI_Snprintf(def, def_len, format, option, arg);
1047     AddOption(def, NULL);
1048 }
1049 
1050 static void
1051 SetMainModule(const char *s)
1052 {
1053     static const char format[] = "-Djdk.module.main=%s";
1054     char* slash = JLI_StrChr(s, '/');
1055     size_t s_len, def_len;
1056     char *def;
1057 
1058     /* value may be <module> or <module>/<mainclass> */
1059     if (slash == NULL) {
1060         s_len = JLI_StrLen(s);
1061     } else {
1062         s_len = (size_t) (slash - s);
1063     }
1064     def_len = sizeof(format)
1065                - 2 /* strlen("%s") */
1066                + s_len;
1067     def = JLI_MemAlloc(def_len);
1068     JLI_Snprintf(def, def_len, format, s);
1069     AddOption(def, NULL);
1070 }
1071 
1072 /*
1073  * Test if the current argv is an option, i.e. with a leading `-`
1074  * and followed with an argument without a leading `-`.
1075  */
1076 static jboolean
1077 IsOptionWithArgument(int argc, char** argv) {
1078     char* option;
1079     char* arg;
1080 
1081     if (argc <= 1)
1082         return JNI_FALSE;
1083 
1084     option = *argv;
1085     arg = *(argv+1);
1086     return *option == '-' && *arg != '-';
1087 }
1088 
1089 /*
1090  * Gets the option, and its argument if the option has an argument.
1091  * It will update *pargc, **pargv to the next option.
1092  */
1093 static int
1094 GetOpt(int *pargc, char ***pargv, char **poption, char **pvalue) {
1095     int argc = *pargc;
1096     char** argv = *pargv;
1097     char* arg = *argv;
1098 
1099     char* option = arg;
1100     char* value = NULL;
1101     char* equals = NULL;
1102     int kind = LAUNCHER_OPTION;
1103     jboolean has_arg = JNI_FALSE;
1104 
1105     // check if this option may be a white-space option with an argument
1106     has_arg = IsOptionWithArgument(argc, argv);
1107 
1108     argv++; --argc;
1109     if (IsLauncherOption(arg)) {
1110         if (has_arg) {
1111             value = *argv;
1112             argv++; --argc;
1113         }
1114         kind = IsLauncherMainOption(arg) ? LAUNCHER_MAIN_OPTION
1115                                          : LAUNCHER_OPTION_WITH_ARGUMENT;
1116     } else if (IsModuleOption(arg)) {
1117         kind = VM_LONG_OPTION_WITH_ARGUMENT;
1118         if (has_arg) {
1119             value = *argv;
1120             argv++; --argc;
1121         }
1122 
1123         /*
1124          * Support short form alias
1125          */
1126         if (JLI_StrCmp(arg, "-p") == 0) {
1127             option = "--module-path";
1128         }
1129 
1130     } else if (JLI_StrCCmp(arg, "--") == 0 && (equals = JLI_StrChr(arg, '=')) != NULL) {
1131         value = equals+1;
1132         if (JLI_StrCCmp(arg, "--describe-module=") == 0 ||
1133             JLI_StrCCmp(arg, "--module=") == 0 ||
1134             JLI_StrCCmp(arg, "--class-path=") == 0||
1135             JLI_StrCCmp(arg, "--source=") == 0) {
1136             kind = LAUNCHER_OPTION_WITH_ARGUMENT;
1137         } else {
1138             kind = VM_LONG_OPTION;
1139         }
1140     }
1141 
1142     *pargc = argc;
1143     *pargv = argv;
1144     *poption = option;
1145     *pvalue = value;
1146     return kind;
1147 }
1148 
1149 /*
1150  * Parses command line arguments.  Returns JNI_FALSE if launcher
1151  * should exit without starting vm, returns JNI_TRUE if vm needs
1152  * to be started to process given options.  *pret (the launcher
1153  * process return value) is set to 0 for a normal exit.
1154  */
1155 static jboolean
1156 ParseArguments(int *pargc, char ***pargv,
1157                int *pmode, char **pwhat,
1158                int *pret)
1159 {
1160     int argc = *pargc;
1161     char **argv = *pargv;
1162     int mode = LM_UNKNOWN;
1163     char *arg = NULL;
1164     bool headless = false;
1165     char *splash_file_path = NULL; // value of "-splash:" option
1166 
1167     *pret = 0;
1168 
1169     while (argc > 0 && *(arg = *argv) == '-') {
1170         char *option = NULL;
1171         char *value = NULL;
1172         int kind = GetOpt(&argc, &argv, &option, &value);
1173         jboolean has_arg = value != NULL && JLI_StrLen(value) > 0;
1174         jboolean has_arg_any_len = value != NULL;
1175 
1176 /*
1177  * Option to set main entry point
1178  */
1179         if (JLI_StrCmp(arg, "-jar") == 0) {
1180             ARG_CHECK(argc, ARG_ERROR2, arg);
1181             mode = checkMode(mode, LM_JAR, arg);
1182         } else if (JLI_StrCmp(arg, "--module") == 0 ||
1183                    JLI_StrCCmp(arg, "--module=") == 0 ||
1184                    JLI_StrCmp(arg, "-m") == 0) {
1185             REPORT_ERROR (has_arg, ARG_ERROR5, arg);
1186             SetMainModule(value);
1187             mode = checkMode(mode, LM_MODULE, arg);
1188             if (has_arg) {
1189                *pwhat = value;
1190                 break;
1191             }
1192         } else if (JLI_StrCmp(arg, "--source") == 0 ||
1193                    JLI_StrCCmp(arg, "--source=") == 0) {
1194             REPORT_ERROR (has_arg, ARG_ERROR13, arg);
1195             mode = LM_SOURCE;
1196             if (has_arg) {
1197                 const char *prop = "-Djdk.internal.javac.source=";
1198                 size_t size = JLI_StrLen(prop) + JLI_StrLen(value) + 1;
1199                 char *propValue = (char *)JLI_MemAlloc(size);
1200                 JLI_Snprintf(propValue, size, "%s%s", prop, value);
1201                 AddOption(propValue, NULL);
1202             }
1203         } else if (JLI_StrCmp(arg, "--class-path") == 0 ||
1204                    JLI_StrCCmp(arg, "--class-path=") == 0 ||
1205                    JLI_StrCmp(arg, "-classpath") == 0 ||
1206                    JLI_StrCmp(arg, "-cp") == 0) {
1207             REPORT_ERROR (has_arg_any_len, ARG_ERROR1, arg);
1208             SetClassPath(value);
1209         } else if (JLI_StrCmp(arg, "--list-modules") == 0) {
1210             listModules = JNI_TRUE;
1211         } else if (JLI_StrCmp(arg, "--show-resolved-modules") == 0) {
1212             showResolvedModules = JNI_TRUE;
1213         } else if (JLI_StrCmp(arg, "--validate-modules") == 0) {
1214             AddOption("-Djdk.module.validation=true", NULL);
1215             validateModules = JNI_TRUE;
1216         } else if (JLI_StrCmp(arg, "--describe-module") == 0 ||
1217                    JLI_StrCCmp(arg, "--describe-module=") == 0 ||
1218                    JLI_StrCmp(arg, "-d") == 0) {
1219             REPORT_ERROR (has_arg_any_len, ARG_ERROR12, arg);
1220             describeModule = value;
1221 /*
1222  * Parse white-space options
1223  */
1224         } else if (has_arg) {
1225             if (kind == VM_LONG_OPTION) {
1226                 AddOption(option, NULL);
1227             } else if (kind == VM_LONG_OPTION_WITH_ARGUMENT) {
1228                 AddLongFormOption(option, value);
1229             }
1230 /*
1231  * Error missing argument
1232  */
1233         } else if (!has_arg && (JLI_StrCmp(arg, "--module-path") == 0 ||
1234                                 JLI_StrCmp(arg, "-p") == 0 ||
1235                                 JLI_StrCmp(arg, "--upgrade-module-path") == 0)) {
1236             REPORT_ERROR (has_arg, ARG_ERROR4, arg);
1237 
1238         } else if (!has_arg && (IsModuleOption(arg) || IsLongFormModuleOption(arg))) {
1239             REPORT_ERROR (has_arg, ARG_ERROR6, arg);
1240 /*
1241  * The following cases will cause the argument parsing to stop
1242  */
1243         } else if (JLI_StrCmp(arg, "-help") == 0 ||
1244                    JLI_StrCmp(arg, "-h") == 0 ||
1245                    JLI_StrCmp(arg, "-?") == 0) {
1246             printUsageKind = HELP_FULL;
1247             return JNI_TRUE;
1248         } else if (JLI_StrCmp(arg, "--help") == 0) {
1249             printUsageKind = HELP_FULL;
1250             printTo = USE_STDOUT;
1251             return JNI_TRUE;
1252         } else if (JLI_StrCmp(arg, "-version") == 0) {
1253             printVersion = JNI_TRUE;
1254             return JNI_TRUE;
1255         } else if (JLI_StrCmp(arg, "--version") == 0) {
1256             printVersion = JNI_TRUE;
1257             printTo = USE_STDOUT;
1258             return JNI_TRUE;
1259         } else if (JLI_StrCmp(arg, "-showversion") == 0) {
1260             showVersion = JNI_TRUE;
1261         } else if (JLI_StrCmp(arg, "--show-version") == 0) {
1262             showVersion = JNI_TRUE;
1263             printTo = USE_STDOUT;
1264         } else if (JLI_StrCmp(arg, "--dry-run") == 0) {
1265             dryRun = JNI_TRUE;
1266         } else if (JLI_StrCmp(arg, "-X") == 0) {
1267             printUsageKind = HELP_EXTRA;
1268             return JNI_TRUE;
1269         } else if (JLI_StrCmp(arg, "--help-extra") == 0) {
1270             printUsageKind = HELP_EXTRA;
1271             printTo = USE_STDOUT;
1272             return JNI_TRUE;
1273 /*
1274  * The following case checks for -XshowSettings OR -XshowSetting:SUBOPT.
1275  * In the latter case, any SUBOPT value not recognized will default to "all"
1276  */
1277         } else if (JLI_StrCmp(arg, "-XshowSettings") == 0 ||
1278                    JLI_StrCCmp(arg, "-XshowSettings:") == 0) {
1279             showSettings = arg;
1280         } else if (JLI_StrCmp(arg, "-Xdiag") == 0) {
1281             AddOption("-Dsun.java.launcher.diag=true", NULL);
1282         } else if (JLI_StrCmp(arg, "--show-module-resolution") == 0) {
1283             AddOption("-Djdk.module.showModuleResolution=true", NULL);
1284 /*
1285  * The following case provide backward compatibility with old-style
1286  * command line options.
1287  */
1288         } else if (JLI_StrCmp(arg, "-fullversion") == 0) {
1289             JLI_ReportMessage("%s full version \"%s\"", _launcher_name, GetFullVersion());
1290             return JNI_FALSE;
1291         } else if (JLI_StrCmp(arg, "--full-version") == 0) {
1292             JLI_ShowMessage("%s %s", _launcher_name, GetFullVersion());
1293             return JNI_FALSE;
1294         } else if (JLI_StrCmp(arg, "-verbosegc") == 0) {
1295             JLI_ReportErrorMessage(ARG_DEPRECATED, "-verbosegc");
1296             AddOption("-verbose:gc", NULL);
1297         } else if (JLI_StrCmp(arg, "-debug") == 0) {
1298             JLI_ReportErrorMessage(ARG_DEPRECATED, "-debug");
1299         } else if (JLI_StrCmp(arg, "-noclassgc") == 0) {
1300             JLI_ReportErrorMessage(ARG_DEPRECATED, "-noclassgc");
1301             AddOption("-Xnoclassgc", NULL);
1302         } else if (JLI_StrCmp(arg, "-verify") == 0) {
1303             JLI_ReportErrorMessage(ARG_DEPRECATED, "-verify");
1304             AddOption("-Xverify:all", NULL);
1305         } else if (JLI_StrCmp(arg, "-verifyremote") == 0) {
1306             JLI_ReportErrorMessage(ARG_DEPRECATED, "-verifyremote");
1307             AddOption("-Xverify:remote", NULL);
1308         } else if (JLI_StrCmp(arg, "-noverify") == 0) {
1309             /*
1310              * Note that no 'deprecated' message is needed here because the VM
1311              * issues 'deprecated' messages for -noverify and -Xverify:none.
1312              */
1313             AddOption("-Xverify:none", NULL);
1314         } else if (JLI_StrCCmp(arg, "-ss") == 0 ||
1315                    JLI_StrCCmp(arg, "-ms") == 0 ||
1316                    JLI_StrCCmp(arg, "-mx") == 0) {
1317             JLI_ReportErrorMessage("Warning: %.3s option is deprecated"
1318                                    " and may be removed in a future release.", arg);
1319             size_t tmpSize = JLI_StrLen(arg) + 6;
1320             char *tmp = JLI_MemAlloc(tmpSize);
1321             snprintf(tmp, tmpSize, "-X%s", arg + 1); /* skip '-' */
1322             AddOption(tmp, NULL);
1323         } else if (JLI_StrCCmp(arg, "-splash:") == 0) {
1324             splash_file_path = arg + 8;
1325         } else if (JLI_StrCmp(arg, "--disable-@files") == 0) {
1326             ; /* Ignore --disable-@files option already handled */
1327         } else if (ProcessPlatformOption(arg)) {
1328             ; /* Processing of platform dependent options */
1329         } else {
1330             /* java.class.path set on the command line */
1331             if (JLI_StrCCmp(arg, "-Djava.class.path=") == 0) {
1332                 _have_classpath = JNI_TRUE;
1333             } else if (JLI_StrCmp(arg, "-Djava.awt.headless=true") == 0) {
1334                 /*
1335                  * Checking for headless toolkit option in the same way as AWT does:
1336                  * "true" means true and any other value means false
1337                  */
1338                 headless = true;
1339             } else if (JLI_StrCCmp(arg, "-Djava.awt.headless=") == 0) {
1340                 headless = false;
1341             }
1342             AddOption(arg, NULL);
1343         }
1344 
1345         /*
1346         * Check for CDS option
1347         */
1348         if (JLI_StrCmp(arg, "-Xshare:dump") == 0) {
1349             dumpSharedSpaces = JNI_TRUE;
1350         }
1351         if (JLI_StrCmp(arg, "-XX:AOTMode=create") == 0) {
1352             // Alias for -Xshare:dump
1353             dumpSharedSpaces = JNI_TRUE;
1354         }
1355     }
1356 
1357     if (*pwhat == NULL && --argc >= 0) {
1358         *pwhat = *argv++;
1359     }
1360 
1361     if (*pwhat == NULL) {
1362         /* LM_UNKNOWN okay for options that exit */
1363         if (!listModules && !describeModule && !validateModules && !dumpSharedSpaces) {
1364             *pret = 1;
1365             printUsageKind = HELP_CONCISE;
1366         }
1367     } else if (mode == LM_UNKNOWN) {
1368         if (!_have_classpath) {
1369             SetClassPath(".");
1370         }
1371         /* If neither of -m, -jar, --source option is set, then the
1372          * launcher mode is LM_UNKNOWN. In such cases, we determine the
1373          * mode as LM_CLASS or LM_SOURCE per the input file. */
1374         mode = IsSourceFile(arg) ? LM_SOURCE : LM_CLASS;
1375     } else if (mode == LM_CLASS && IsSourceFile(arg)) {
1376         /* override LM_CLASS mode if given a source file */
1377         mode = LM_SOURCE;
1378     }
1379 
1380     if (mode == LM_SOURCE) {
1381         // communicate the launcher mode to runtime
1382         AddOption("-Dsun.java.launcher.mode=source", NULL);
1383         AddOption("--add-modules=ALL-DEFAULT", NULL);
1384         *pwhat = SOURCE_LAUNCHER_MAIN_ENTRY;
1385         // adjust (argc, argv) so that the name of the source file
1386         // is included in the args passed to the source launcher
1387         // main entry class
1388         *pargc = argc + 1;
1389         *pargv = argv - 1;
1390     } else {
1391         if (argc >= 0) {
1392             *pargc = argc;
1393             *pargv = argv;
1394         }
1395     }
1396 
1397     *pmode = mode;
1398 
1399     if (!headless) {
1400         char *jar_path = NULL;
1401         if (mode == LM_JAR) {
1402             jar_path = *pwhat;
1403         }
1404         // Not in headless mode. We now set a couple of env variables that
1405         // will be used later by ShowSplashScreen().
1406         SetupSplashScreenEnvVars(splash_file_path, jar_path);
1407     }
1408 
1409     return JNI_TRUE;
1410 }
1411 
1412 /*
1413  * Sets the relevant environment variables that are subsequently used by
1414  * the ShowSplashScreen() function. The splash_file_path and jar_path parameters
1415  * are used to determine which environment variables to set.
1416  * The splash_file_path is the value that was provided to the "-splash:" option
1417  * when launching java. It may be null, which implies the "-splash:" option wasn't used.
1418  * The jar_path is the value that was provided to the "-jar" option when launching java.
1419  * It too may be null, which implies the "-jar" option wasn't used.
1420  */
1421 static void
1422 SetupSplashScreenEnvVars(const char *splash_file_path, char *jar_path) {
1423     // Command line specified "-splash:" takes priority over manifest one.
1424     if (splash_file_path) {
1425         // We set up the splash file name as a env variable which then gets
1426         // used when showing the splash screen in ShowSplashScreen().
1427 
1428         // create the string of the form _JAVA_SPLASH_FILE=<val>
1429         splash_file_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_FILE_ENV_ENTRY "=")
1430                                          + JLI_StrLen(splash_file_path) + 1);
1431         JLI_StrCpy(splash_file_entry, SPLASH_FILE_ENV_ENTRY "=");
1432         JLI_StrCat(splash_file_entry, splash_file_path);
1433         putenv(splash_file_entry);
1434         return;
1435     }
1436     if (!jar_path) {
1437         // no jar to look into for "SplashScreen-Image" manifest attribute
1438         return;
1439     }
1440     // parse the jar's manifest to find any "SplashScreen-Image"
1441     int res = 0;
1442     manifest_info  info;
1443     if ((res = JLI_ParseManifest(jar_path, &info)) != 0) {
1444         JLI_FreeManifest(); // cleanup any manifest structure
1445         if (res == -1) {
1446             JLI_ReportErrorMessage(JAR_ERROR2, jar_path);
1447         } else {
1448             JLI_ReportErrorMessage(JAR_ERROR3, jar_path);
1449         }
1450         exit(1);
1451     }
1452     if (!info.splashscreen_image_file_name) {
1453         JLI_FreeManifest(); // cleanup the manifest structure
1454         // no "SplashScreen-Image" in jar's manifest
1455         return;
1456     }
1457     // The jar's manifest had a "Splashscreen-Image" specified. We set up the jar entry name
1458     // and the jar file name as env variables which then get used when showing the splash screen
1459     // in ShowSplashScreen().
1460 
1461     // create the string of the form _JAVA_SPLASH_FILE=<val>
1462     splash_file_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_FILE_ENV_ENTRY "=")
1463                                      + JLI_StrLen(info.splashscreen_image_file_name) + 1);
1464     JLI_StrCpy(splash_file_entry, SPLASH_FILE_ENV_ENTRY "=");
1465     JLI_StrCat(splash_file_entry, info.splashscreen_image_file_name);
1466     putenv(splash_file_entry);
1467     // create the string of the form _JAVA_SPLASH_JAR=<val>
1468     splash_jar_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_JAR_ENV_ENTRY "=") + JLI_StrLen(jar_path) + 1);
1469     JLI_StrCpy(splash_jar_entry, SPLASH_JAR_ENV_ENTRY "=");
1470     JLI_StrCat(splash_jar_entry, jar_path);
1471     putenv(splash_jar_entry);
1472     JLI_FreeManifest(); // cleanup the manifest structure
1473 }
1474 
1475 /*
1476  * Initializes the Java Virtual Machine. Also frees options array when
1477  * finished.
1478  */
1479 static jboolean
1480 InitializeJVM(JavaVM **pvm, JNIEnv **penv, InvocationFunctions *ifn)
1481 {
1482     JavaVMInitArgs args;
1483     jint r;
1484 
1485     memset(&args, 0, sizeof(args));
1486     args.version  = JNI_VERSION_1_2;
1487     args.nOptions = numOptions;
1488     args.options  = options;
1489     args.ignoreUnrecognized = JNI_FALSE;
1490 
1491     if (JLI_IsTraceLauncher()) {
1492         int i = 0;
1493         printf("JavaVM args:\n    ");
1494         printf("version 0x%08lx, ", (long)args.version);
1495         printf("ignoreUnrecognized is %s, ",
1496                args.ignoreUnrecognized ? "JNI_TRUE" : "JNI_FALSE");
1497         printf("nOptions is %ld\n", (long)args.nOptions);
1498         for (i = 0; i < numOptions; i++)
1499             printf("    option[%2d] = '%s'\n",
1500                    i, args.options[i].optionString);
1501     }
1502 
1503     r = ifn->CreateJavaVM(pvm, (void **)penv, &args);
1504     JLI_MemFree(options);
1505     return r == JNI_OK;
1506 }
1507 
1508 static jclass helperClass = NULL;
1509 
1510 jclass
1511 GetLauncherHelperClass(JNIEnv *env)
1512 {
1513     if (helperClass == NULL) {
1514         NULL_CHECK0(helperClass = FindBootStrapClass(env,
1515                 "sun/launcher/LauncherHelper"));
1516     }
1517     return helperClass;
1518 }
1519 
1520 static jmethodID makePlatformStringMID = NULL;
1521 /*
1522  * Returns a new Java string object for the specified platform string.
1523  */
1524 static jstring
1525 NewPlatformString(JNIEnv *env, char *s)
1526 {
1527     int len = (int)JLI_StrLen(s);
1528     jbyteArray ary;
1529     jclass cls = GetLauncherHelperClass(env);
1530     NULL_CHECK0(cls);
1531     if (s == NULL)
1532         return 0;
1533 
1534     ary = (*env)->NewByteArray(env, len);
1535     if (ary != 0) {
1536         jstring str = 0;
1537         (*env)->SetByteArrayRegion(env, ary, 0, len, (jbyte *)s);
1538         if (!(*env)->ExceptionCheck(env)) {
1539             if (makePlatformStringMID == NULL) {
1540                 NULL_CHECK0(makePlatformStringMID = (*env)->GetStaticMethodID(env,
1541                         cls, "makePlatformString", "(Z[B)Ljava/lang/String;"));
1542             }
1543             str = (*env)->CallStaticObjectMethod(env, cls,
1544                     makePlatformStringMID, USE_STDERR, ary);
1545             CHECK_EXCEPTION_RETURN_VALUE(0);
1546             (*env)->DeleteLocalRef(env, ary);
1547             return str;
1548         }
1549     }
1550     return 0;
1551 }
1552 
1553 /*
1554  * Returns a new array of Java string objects for the specified
1555  * array of platform strings.
1556  */
1557 jobjectArray
1558 NewPlatformStringArray(JNIEnv *env, char **strv, int strc)
1559 {
1560     jarray cls;
1561     jarray ary;
1562     int i;
1563 
1564     NULL_CHECK0(cls = FindBootStrapClass(env, "java/lang/String"));
1565     NULL_CHECK0(ary = (*env)->NewObjectArray(env, strc, cls, 0));
1566     CHECK_EXCEPTION_RETURN_VALUE(0);
1567     for (i = 0; i < strc; i++) {
1568         jstring str = NewPlatformString(env, *strv++);
1569         NULL_CHECK0(str);
1570         (*env)->SetObjectArrayElement(env, ary, i, str);
1571         (*env)->DeleteLocalRef(env, str);
1572     }
1573     return ary;
1574 }
1575 
1576 /*
1577  * Calls LauncherHelper::checkAndLoadMain to verify that the main class
1578  * is present, it is ok to load the main class and then load the main class.
1579  * For more details refer to the java implementation.
1580  */
1581 static jclass
1582 LoadMainClass(JNIEnv *env, int mode, char *name)
1583 {
1584     jmethodID mid;
1585     jstring str;
1586     jobject result;
1587     jlong start = 0, end = 0;
1588     jclass cls = GetLauncherHelperClass(env);
1589     NULL_CHECK0(cls);
1590     if (JLI_IsTraceLauncher()) {
1591         start = CurrentTimeMicros();
1592     }
1593     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1594                 "checkAndLoadMain",
1595                 "(ZILjava/lang/String;)Ljava/lang/Class;"));
1596 
1597     NULL_CHECK0(str = NewPlatformString(env, name));
1598     NULL_CHECK0(result = (*env)->CallStaticObjectMethod(env, cls, mid,
1599                                                         USE_STDERR, mode, str));
1600 
1601     if (JLI_IsTraceLauncher()) {
1602         end = CurrentTimeMicros();
1603         printf("%ld micro seconds to load main class\n", (long)(end-start));
1604         printf("----%s----\n", JLDEBUG_ENV_ENTRY);
1605     }
1606 
1607     return (jclass)result;
1608 }
1609 
1610 static jclass
1611 GetApplicationClass(JNIEnv *env)
1612 {
1613     jmethodID mid;
1614     jclass appClass;
1615     jclass cls = GetLauncherHelperClass(env);
1616     NULL_CHECK0(cls);
1617     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1618                 "getApplicationClass",
1619                 "()Ljava/lang/Class;"));
1620 
1621     appClass = (*env)->CallStaticObjectMethod(env, cls, mid);
1622     CHECK_EXCEPTION_RETURN_VALUE(0);
1623     return appClass;
1624 }
1625 
1626 static char* expandWildcardOnLongOpt(char* arg) {
1627     char *p, *value;
1628     size_t optLen, valueLen;
1629     p = JLI_StrChr(arg, '=');
1630 
1631     if (p == NULL || p[1] == '\0') {
1632         JLI_ReportErrorMessage(ARG_ERROR1, arg);
1633         exit(1);
1634     }
1635     p++;
1636     value = (char *) JLI_WildcardExpandClasspath(p);
1637     if (p == value) {
1638         // no wildcard
1639         return arg;
1640     }
1641 
1642     optLen = p - arg;
1643     valueLen = JLI_StrLen(value);
1644     p = JLI_MemAlloc(optLen + valueLen + 1);
1645     memcpy(p, arg, optLen);
1646     memcpy(p + optLen, value, valueLen);
1647     p[optLen + valueLen] = '\0';
1648     return p;
1649 }
1650 
1651 /*
1652  * For tools, convert command line args thus:
1653  *   javac -cp foo:foo/"*" -J-ms32m ...
1654  *   java -ms32m -cp JLI_WildcardExpandClasspath(foo:foo/"*") ...
1655  *
1656  * Takes 4 parameters, and returns the populated arguments
1657  */
1658 static void
1659 TranslateApplicationArgs(int jargc, const char **jargv, int *pargc, char ***pargv)
1660 {
1661     int argc = *pargc;
1662     char **argv = *pargv;
1663     int nargc = argc + jargc;
1664     char **nargv = JLI_MemAlloc((nargc + 1) * sizeof(char *));
1665     int i;
1666 
1667     *pargc = nargc;
1668     *pargv = nargv;
1669 
1670     /* Copy the VM arguments (i.e. prefixed with -J) */
1671     for (i = 0; i < jargc; i++) {
1672         const char *arg = jargv[i];
1673         if (arg[0] == '-' && arg[1] == 'J') {
1674             assert(arg[2] != '\0' && "Invalid JAVA_ARGS or EXTRA_JAVA_ARGS defined by build");
1675             *nargv++ = JLI_StringDup(arg + 2);
1676         }
1677     }
1678 
1679     for (i = 0; i < argc; i++) {
1680         char *arg = argv[i];
1681         if (arg[0] == '-' && arg[1] == 'J') {
1682             if (arg[2] == '\0') {
1683                 JLI_ReportErrorMessage(ARG_ERROR3);
1684                 exit(1);
1685             }
1686             *nargv++ = arg + 2;
1687         }
1688     }
1689 
1690     /* Copy the rest of the arguments */
1691     for (i = 0; i < jargc ; i++) {
1692         const char *arg = jargv[i];
1693         if (arg[0] != '-' || arg[1] != 'J') {
1694             *nargv++ = (arg == NULL) ? NULL : JLI_StringDup(arg);
1695         }
1696     }
1697     for (i = 0; i < argc; i++) {
1698         char *arg = argv[i];
1699         if (arg[0] == '-') {
1700             if (arg[1] == 'J')
1701                 continue;
1702             if (IsWildCardEnabled()) {
1703                 if (IsClassPathOption(arg) && i < argc - 1) {
1704                     *nargv++ = arg;
1705                     *nargv++ = (char *) JLI_WildcardExpandClasspath(argv[i+1]);
1706                     i++;
1707                     continue;
1708                 }
1709                 if (JLI_StrCCmp(arg, "--class-path=") == 0) {
1710                     *nargv++ = expandWildcardOnLongOpt(arg);
1711                     continue;
1712                 }
1713             }
1714         }
1715         *nargv++ = arg;
1716     }
1717     *nargv = 0;
1718 }
1719 
1720 /*
1721  * For our tools, we try to add 3 VM options:
1722  *      -Denv.class.path=<envcp>
1723  *      -Dapplication.home=<apphome>
1724  *      -Djava.class.path=<appcp>
1725  * <envcp>   is the user's setting of CLASSPATH -- for instance the user
1726  *           tells javac where to find binary classes through this environment
1727  *           variable.  Notice that users will be able to compile against our
1728  *           tools classes (sun.tools.javac.Main) only if they explicitly add
1729  *           tools.jar to CLASSPATH.
1730  * <apphome> is the directory where the application is installed.
1731  * <appcp>   is the classpath to where our apps' classfiles are.
1732  */
1733 static jboolean
1734 AddApplicationOptions(int cpathc, const char **cpathv)
1735 {
1736     char *envcp, *appcp, *apphome;
1737     char home[MAXPATHLEN]; /* application home */
1738     char separator[] = { PATH_SEPARATOR, '\0' };
1739     int size, i;
1740 
1741     {
1742         const char *s = getenv("CLASSPATH");
1743         if (s) {
1744             s = (char *) JLI_WildcardExpandClasspath(s);
1745             /* 40 for -Denv.class.path= */
1746             if (JLI_StrLen(s) + 40 > JLI_StrLen(s)) { // Safeguard from overflow
1747                 size_t envcpSize = JLI_StrLen(s) + 40;
1748                 envcp = (char *)JLI_MemAlloc(envcpSize);
1749                 snprintf(envcp, envcpSize, "-Denv.class.path=%s", s);
1750                 AddOption(envcp, NULL);
1751             }
1752         }
1753     }
1754 
1755     if (!GetApplicationHome(home, sizeof(home))) {
1756         JLI_ReportErrorMessage(CFG_ERROR5);
1757         return JNI_FALSE;
1758     }
1759 
1760     /* 40 for '-Dapplication.home=' */
1761     size_t apphomeSize = JLI_StrLen(home) + 40;
1762     apphome = (char *)JLI_MemAlloc(apphomeSize);
1763     snprintf(apphome, apphomeSize, "-Dapplication.home=%s", home);
1764     AddOption(apphome, NULL);
1765 
1766     /* How big is the application's classpath? */
1767     if (cpathc > 0) {
1768         size = 40;                                 /* 40: "-Djava.class.path=" */
1769         for (i = 0; i < cpathc; i++) {
1770             size += (int)JLI_StrLen(home) + (int)JLI_StrLen(cpathv[i]) + 1; /* 1: separator */
1771         }
1772         appcp = (char *)JLI_MemAlloc(size + 1);
1773         JLI_StrCpy(appcp, "-Djava.class.path=");
1774         for (i = 0; i < cpathc; i++) {
1775             JLI_StrCat(appcp, home);                        /* c:\program files\myapp */
1776             JLI_StrCat(appcp, cpathv[i]);           /* \lib\myapp.jar         */
1777             JLI_StrCat(appcp, separator);           /* ;                      */
1778         }
1779         appcp[JLI_StrLen(appcp)-1] = '\0';  /* remove trailing path separator */
1780         AddOption(appcp, NULL);
1781     }
1782     return JNI_TRUE;
1783 }
1784 
1785 /*
1786  * inject the -Dsun.java.command pseudo property into the args structure
1787  * this pseudo property is used in the HotSpot VM to expose the
1788  * Java class name and arguments to the main method to the VM. The
1789  * HotSpot VM uses this pseudo property to store the Java class name
1790  * (or jar file name) and the arguments to the class's main method
1791  * to the instrumentation memory region. The sun.java.command pseudo
1792  * property is not exported by HotSpot to the Java layer.
1793  */
1794 void
1795 SetJavaCommandLineProp(char *what, int argc, char **argv)
1796 {
1797 
1798     int i = 0;
1799     size_t len = 0;
1800     char* javaCommand = NULL;
1801     char* dashDstr = "-Dsun.java.command=";
1802 
1803     if (what == NULL) {
1804         /* unexpected, one of these should be set. just return without
1805          * setting the property
1806          */
1807         return;
1808     }
1809 
1810     /* determine the amount of memory to allocate assuming
1811      * the individual components will be space separated
1812      */
1813     len = JLI_StrLen(what);
1814     for (i = 0; i < argc; i++) {
1815         len += JLI_StrLen(argv[i]) + 1;
1816     }
1817 
1818     /* allocate the memory */
1819     javaCommand = (char*) JLI_MemAlloc(len + JLI_StrLen(dashDstr) + 1);
1820 
1821     /* build the -D string */
1822     *javaCommand = '\0';
1823     JLI_StrCat(javaCommand, dashDstr);
1824     JLI_StrCat(javaCommand, what);
1825 
1826     for (i = 0; i < argc; i++) {
1827         /* the components of the string are space separated. In
1828          * the case of embedded white space, the relationship of
1829          * the white space separated components to their true
1830          * positional arguments will be ambiguous. This issue may
1831          * be addressed in a future release.
1832          */
1833         JLI_StrCat(javaCommand, " ");
1834         JLI_StrCat(javaCommand, argv[i]);
1835     }
1836 
1837     AddOption(javaCommand, NULL);
1838 }
1839 
1840 /*
1841  * JVM would like to know if it's created by a standard Sun launcher, or by
1842  * user native application, the following property indicates the former.
1843  */
1844 static void SetJavaLauncherProp() {
1845   AddOption("-Dsun.java.launcher=SUN_STANDARD", NULL);
1846 }
1847 
1848 /*
1849  * Prints the version information from the java.version and other properties.
1850  */
1851 static void
1852 PrintJavaVersion(JNIEnv *env)
1853 {
1854     jclass ver;
1855     jmethodID print;
1856 
1857     NULL_CHECK(ver = FindBootStrapClass(env, "java/lang/VersionProps"));
1858     NULL_CHECK(print = (*env)->GetStaticMethodID(env,
1859                                                  ver,
1860                                                  "print",
1861                                                  "(Z)V"
1862                                                  )
1863               );
1864 
1865     (*env)->CallStaticVoidMethod(env, ver, print, printTo);
1866 }
1867 
1868 /*
1869  * Prints all the Java settings, see the java implementation for more details.
1870  */
1871 static void
1872 ShowSettings(JNIEnv *env, char *optString)
1873 {
1874     jmethodID showSettingsID;
1875     jstring joptString;
1876     jclass cls = GetLauncherHelperClass(env);
1877     NULL_CHECK(cls);
1878     NULL_CHECK(showSettingsID = (*env)->GetStaticMethodID(env, cls,
1879             "showSettings", "(ZLjava/lang/String;JJJ)V"));
1880     NULL_CHECK(joptString = (*env)->NewStringUTF(env, optString));
1881     (*env)->CallStaticVoidMethod(env, cls, showSettingsID,
1882                                  USE_STDERR,
1883                                  joptString,
1884                                  (jlong)initialHeapSize,
1885                                  (jlong)maxHeapSize,
1886                                  (jlong)threadStackSize);
1887 }
1888 
1889 /**
1890  * Show resolved modules
1891  */
1892 static void
1893 ShowResolvedModules(JNIEnv *env)
1894 {
1895     jmethodID showResolvedModulesID;
1896     jclass cls = GetLauncherHelperClass(env);
1897     NULL_CHECK(cls);
1898     NULL_CHECK(showResolvedModulesID = (*env)->GetStaticMethodID(env, cls,
1899             "showResolvedModules", "()V"));
1900     (*env)->CallStaticVoidMethod(env, cls, showResolvedModulesID);
1901 }
1902 
1903 /**
1904  * List observable modules
1905  */
1906 static void
1907 ListModules(JNIEnv *env)
1908 {
1909     jmethodID listModulesID;
1910     jclass cls = GetLauncherHelperClass(env);
1911     NULL_CHECK(cls);
1912     NULL_CHECK(listModulesID = (*env)->GetStaticMethodID(env, cls,
1913             "listModules", "()V"));
1914     (*env)->CallStaticVoidMethod(env, cls, listModulesID);
1915 }
1916 
1917 /**
1918  * Describe a module
1919  */
1920 static void
1921 DescribeModule(JNIEnv *env, char *optString)
1922 {
1923     jmethodID describeModuleID;
1924     jstring joptString = NULL;
1925     jclass cls = GetLauncherHelperClass(env);
1926     NULL_CHECK(cls);
1927     NULL_CHECK(describeModuleID = (*env)->GetStaticMethodID(env, cls,
1928             "describeModule", "(Ljava/lang/String;)V"));
1929     NULL_CHECK(joptString = NewPlatformString(env, optString));
1930     (*env)->CallStaticVoidMethod(env, cls, describeModuleID, joptString);
1931 }
1932 
1933 /*
1934  * Prints default usage or the Xusage message, see sun.launcher.LauncherHelper.java
1935  */
1936 static void
1937 PrintUsage(JNIEnv* env, enum HelpKind printUsageKind)
1938 {
1939   jmethodID initHelp, vmSelect, vmSynonym;
1940   jmethodID printHelp, printConciseUsageMessage, printXUsageMessage;
1941   jstring jprogname, vm1, vm2;
1942   int i;
1943   jclass cls = GetLauncherHelperClass(env);
1944   NULL_CHECK(cls);
1945   switch (printUsageKind) {
1946     case HELP_NONE: break;
1947     case HELP_CONCISE:
1948       NULL_CHECK(printConciseUsageMessage = (*env)->GetStaticMethodID(env, cls,
1949                                           "printConciseUsageMessage", "(Z)V"));
1950       (*env)->CallStaticVoidMethod(env, cls, printConciseUsageMessage, printTo);
1951       break;
1952     case HELP_EXTRA:
1953       NULL_CHECK(printXUsageMessage = (*env)->GetStaticMethodID(env, cls,
1954                                           "printXUsageMessage", "(Z)V"));
1955       (*env)->CallStaticVoidMethod(env, cls, printXUsageMessage, printTo);
1956       break;
1957     case HELP_FULL:
1958       NULL_CHECK(initHelp = (*env)->GetStaticMethodID(env, cls,
1959                                           "initHelpMessage", "(Ljava/lang/String;)V"));
1960 
1961       NULL_CHECK(vmSelect = (*env)->GetStaticMethodID(env, cls, "appendVmSelectMessage",
1962                                           "(Ljava/lang/String;Ljava/lang/String;)V"));
1963 
1964       NULL_CHECK(vmSynonym = (*env)->GetStaticMethodID(env, cls,
1965                                           "appendVmSynonymMessage",
1966                                           "(Ljava/lang/String;Ljava/lang/String;)V"));
1967 
1968       NULL_CHECK(printHelp = (*env)->GetStaticMethodID(env, cls,
1969                                           "printHelpMessage", "(Z)V"));
1970 
1971       NULL_CHECK(jprogname = (*env)->NewStringUTF(env, _program_name));
1972 
1973       /* Initialize the usage message with the usual preamble */
1974       (*env)->CallStaticVoidMethod(env, cls, initHelp, jprogname);
1975       CHECK_EXCEPTION_RETURN();
1976 
1977 
1978       /* Assemble the other variant part of the usage */
1979       for (i=1; i<knownVMsCount; i++) {
1980         if (knownVMs[i].flag == VM_KNOWN) {
1981           NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
1982           NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].name+1));
1983           (*env)->CallStaticVoidMethod(env, cls, vmSelect, vm1, vm2);
1984           CHECK_EXCEPTION_RETURN();
1985         }
1986       }
1987       for (i=1; i<knownVMsCount; i++) {
1988         if (knownVMs[i].flag == VM_ALIASED_TO) {
1989           NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
1990           NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].alias+1));
1991           (*env)->CallStaticVoidMethod(env, cls, vmSynonym, vm1, vm2);
1992           CHECK_EXCEPTION_RETURN();
1993         }
1994       }
1995 
1996       /* Complete the usage message and print to stderr*/
1997       (*env)->CallStaticVoidMethod(env, cls, printHelp, printTo);
1998       break;
1999   }
2000   return;
2001 }
2002 
2003 /*
2004  * Read the jvm.cfg file and fill the knownJVMs[] array.
2005  *
2006  * The functionality of the jvm.cfg file is subject to change without
2007  * notice and the mechanism will be removed in the future.
2008  *
2009  * The lexical structure of the jvm.cfg file is as follows:
2010  *
2011  *     jvmcfg         :=  { vmLine }
2012  *     vmLine         :=  knownLine
2013  *                    |   aliasLine
2014  *                    |   warnLine
2015  *                    |   ignoreLine
2016  *                    |   errorLine
2017  *                    |   predicateLine
2018  *                    |   commentLine
2019  *     knownLine      :=  flag  "KNOWN"                  EOL
2020  *     warnLine       :=  flag  "WARN"                   EOL
2021  *     ignoreLine     :=  flag  "IGNORE"                 EOL
2022  *     errorLine      :=  flag  "ERROR"                  EOL
2023  *     aliasLine      :=  flag  "ALIASED_TO"       flag  EOL
2024  *     predicateLine  :=  flag  "IF_SERVER_CLASS"  flag  EOL
2025  *     commentLine    :=  "#" text                       EOL
2026  *     flag           :=  "-" identifier
2027  *
2028  * The semantics are that when someone specifies a flag on the command line:
2029  * - if the flag appears on a knownLine, then the identifier is used as
2030  *   the name of the directory holding the JVM library (the name of the JVM).
2031  * - if the flag appears as the first flag on an aliasLine, the identifier
2032  *   of the second flag is used as the name of the JVM.
2033  * - if the flag appears on a warnLine, the identifier is used as the
2034  *   name of the JVM, but a warning is generated.
2035  * - if the flag appears on an ignoreLine, the identifier is recognized as the
2036  *   name of a JVM, but the identifier is ignored and the default vm used
2037  * - if the flag appears on an errorLine, an error is generated.
2038  * - if the flag appears as the first flag on a predicateLine, and
2039  *   the machine on which you are running passes the predicate indicated,
2040  *   then the identifier of the second flag is used as the name of the JVM,
2041  *   otherwise the identifier of the first flag is used as the name of the JVM.
2042  * If no flag is given on the command line, the first vmLine of the jvm.cfg
2043  * file determines the name of the JVM.
2044  * PredicateLines are only interpreted on first vmLine of a jvm.cfg file,
2045  * since they only make sense if someone hasn't specified the name of the
2046  * JVM on the command line.
2047  *
2048  * The intent of the jvm.cfg file is to allow several JVM libraries to
2049  * be installed in different subdirectories of a single JDK installation,
2050  * for space-savings and convenience in testing.
2051  * The intent is explicitly not to provide a full aliasing or predicate
2052  * mechanism.
2053  */
2054 jint
2055 ReadKnownVMs(const char *jvmCfgName, jboolean speculative)
2056 {
2057     FILE *jvmCfg;
2058     char line[MAXPATHLEN+20];
2059     int cnt = 0;
2060     int lineno = 0;
2061     jlong start = 0, end = 0;
2062     int vmType;
2063     char *tmpPtr;
2064     char *altVMName = NULL;
2065     static char *whiteSpace = " \t";
2066     if (JLI_IsTraceLauncher()) {
2067         start = CurrentTimeMicros();
2068     }
2069 
2070     jvmCfg = fopen(jvmCfgName, "r");
2071     if (jvmCfg == NULL) {
2072       if (!speculative) {
2073         JLI_ReportErrorMessage(CFG_ERROR6, jvmCfgName);
2074         exit(1);
2075       } else {
2076         return -1;
2077       }
2078     }
2079     while (fgets(line, sizeof(line), jvmCfg) != NULL) {
2080         vmType = VM_UNKNOWN;
2081         lineno++;
2082         if (line[0] == '#')
2083             continue;
2084         if (line[0] != '-') {
2085             JLI_ReportErrorMessage(CFG_WARN2, lineno, jvmCfgName);
2086         }
2087         if (cnt >= knownVMsLimit) {
2088             GrowKnownVMs(cnt);
2089         }
2090         line[JLI_StrLen(line)-1] = '\0'; /* remove trailing newline */
2091         tmpPtr = line + JLI_StrCSpn(line, whiteSpace);
2092         if (*tmpPtr == 0) {
2093             JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2094         } else {
2095             /* Null-terminate this string for JLI_StringDup below */
2096             *tmpPtr++ = 0;
2097             tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
2098             if (*tmpPtr == 0) {
2099                 JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2100             } else {
2101                 if (!JLI_StrCCmp(tmpPtr, "KNOWN")) {
2102                     vmType = VM_KNOWN;
2103                 } else if (!JLI_StrCCmp(tmpPtr, "ALIASED_TO")) {
2104                     tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
2105                     if (*tmpPtr != 0) {
2106                         tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
2107                     }
2108                     if (*tmpPtr == 0) {
2109                         JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2110                     } else {
2111                         /* Null terminate altVMName */
2112                         altVMName = tmpPtr;
2113                         tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
2114                         *tmpPtr = 0;
2115                         vmType = VM_ALIASED_TO;
2116                     }
2117                 } else if (!JLI_StrCCmp(tmpPtr, "WARN")) {
2118                     vmType = VM_WARN;
2119                 } else if (!JLI_StrCCmp(tmpPtr, "IGNORE")) {
2120                     vmType = VM_IGNORE;
2121                 } else if (!JLI_StrCCmp(tmpPtr, "ERROR")) {
2122                     vmType = VM_ERROR;
2123                 } else if (!JLI_StrCCmp(tmpPtr, "IF_SERVER_CLASS")) {
2124                     /* ignored */
2125                 } else {
2126                     JLI_ReportErrorMessage(CFG_WARN5, lineno, &jvmCfgName[0]);
2127                     vmType = VM_KNOWN;
2128                 }
2129             }
2130         }
2131 
2132         JLI_TraceLauncher("jvm.cfg[%d] = ->%s<-\n", cnt, line);
2133         if (vmType != VM_UNKNOWN) {
2134             knownVMs[cnt].name = JLI_StringDup(line);
2135             knownVMs[cnt].flag = vmType;
2136             switch (vmType) {
2137             default:
2138                 break;
2139             case VM_ALIASED_TO:
2140                 knownVMs[cnt].alias = JLI_StringDup(altVMName);
2141                 JLI_TraceLauncher("    name: %s  vmType: %s  alias: %s\n",
2142                    knownVMs[cnt].name, "VM_ALIASED_TO", knownVMs[cnt].alias);
2143                 break;
2144             }
2145             cnt++;
2146         }
2147     }
2148     fclose(jvmCfg);
2149     knownVMsCount = cnt;
2150 
2151     if (JLI_IsTraceLauncher()) {
2152         end = CurrentTimeMicros();
2153         printf("%ld micro seconds to parse jvm.cfg\n", (long)(end-start));
2154     }
2155 
2156     return cnt;
2157 }
2158 
2159 
2160 static void
2161 GrowKnownVMs(int minimum)
2162 {
2163     struct vmdesc* newKnownVMs;
2164     int newMax;
2165 
2166     newMax = (knownVMsLimit == 0 ? INIT_MAX_KNOWN_VMS : (2 * knownVMsLimit));
2167     if (newMax <= minimum) {
2168         newMax = minimum;
2169     }
2170     newKnownVMs = (struct vmdesc*) JLI_MemAlloc(newMax * sizeof(struct vmdesc));
2171     if (knownVMs != NULL) {
2172         memcpy(newKnownVMs, knownVMs, knownVMsLimit * sizeof(struct vmdesc));
2173     }
2174     JLI_MemFree(knownVMs);
2175     knownVMs = newKnownVMs;
2176     knownVMsLimit = newMax;
2177 }
2178 
2179 
2180 /* Returns index of VM or -1 if not found */
2181 static int
2182 KnownVMIndex(const char* name)
2183 {
2184     int i;
2185     if (JLI_StrCCmp(name, "-J") == 0) name += 2;
2186     for (i = 0; i < knownVMsCount; i++) {
2187         if (!JLI_StrCmp(name, knownVMs[i].name)) {
2188             return i;
2189         }
2190     }
2191     return -1;
2192 }
2193 
2194 static void
2195 FreeKnownVMs()
2196 {
2197     int i;
2198     for (i = 0; i < knownVMsCount; i++) {
2199         JLI_MemFree(knownVMs[i].name);
2200         knownVMs[i].name = NULL;
2201     }
2202     JLI_MemFree(knownVMs);
2203 }
2204 
2205 /*
2206  * Displays the splash screen according to the jar file name
2207  * and image file names stored in environment variables
2208  */
2209 void
2210 ShowSplashScreen()
2211 {
2212     const char *jar_name = getenv(SPLASH_JAR_ENV_ENTRY);
2213     const char *file_name = getenv(SPLASH_FILE_ENV_ENTRY);
2214     int data_size;
2215     void *image_data = NULL;
2216     float scale_factor = 1;
2217     char *scaled_splash_name = NULL;
2218     jboolean isImageScaled = JNI_FALSE;
2219     size_t maxScaledImgNameLength = 0;
2220     if (file_name == NULL){
2221         return;
2222     }
2223 
2224     if (!DoSplashInit()) {
2225         goto exit;
2226     }
2227 
2228     maxScaledImgNameLength = DoSplashGetScaledImgNameMaxPstfixLen(file_name);
2229 
2230     scaled_splash_name = JLI_MemAlloc(
2231                             maxScaledImgNameLength * sizeof(char));
2232     isImageScaled = DoSplashGetScaledImageName(jar_name, file_name,
2233                             &scale_factor,
2234                             scaled_splash_name, maxScaledImgNameLength);
2235     if (jar_name) {
2236 
2237         if (isImageScaled) {
2238             image_data = JLI_JarUnpackFile(
2239                     jar_name, scaled_splash_name, &data_size);
2240         }
2241 
2242         if (!image_data) {
2243             scale_factor = 1;
2244             image_data = JLI_JarUnpackFile(
2245                             jar_name, file_name, &data_size);
2246         }
2247         if (image_data) {
2248             DoSplashSetScaleFactor(scale_factor);
2249             DoSplashLoadMemory(image_data, data_size);
2250             JLI_MemFree(image_data);
2251         } else {
2252             DoSplashClose();
2253         }
2254     } else {
2255         if (isImageScaled) {
2256             DoSplashSetScaleFactor(scale_factor);
2257             DoSplashLoadFile(scaled_splash_name);
2258         } else {
2259             DoSplashLoadFile(file_name);
2260         }
2261     }
2262     JLI_MemFree(scaled_splash_name);
2263 
2264     DoSplashSetFileJarName(file_name, jar_name);
2265 
2266     exit:
2267     /*
2268      * Done with all command line processing and potential re-execs so
2269      * clean up the environment.
2270      */
2271     (void)UnsetEnv(MAIN_CLASS_ENV_ENTRY);
2272     (void)UnsetEnv(SPLASH_FILE_ENV_ENTRY);
2273     (void)UnsetEnv(SPLASH_JAR_ENV_ENTRY);
2274 
2275     JLI_MemFree(splash_jar_entry);
2276     JLI_MemFree(splash_file_entry);
2277 
2278 }
2279 
2280 static const char* GetFullVersion()
2281 {
2282     return _fVersion;
2283 }
2284 
2285 static const char* GetProgramName()
2286 {
2287     return _program_name;
2288 }
2289 
2290 static const char* GetLauncherName()
2291 {
2292     return _launcher_name;
2293 }
2294 
2295 static jboolean IsJavaArgs()
2296 {
2297     return _is_java_args;
2298 }
2299 
2300 static jboolean
2301 IsWildCardEnabled()
2302 {
2303     return _wc_enabled;
2304 }
2305 
2306 int
2307 ContinueInNewThread(InvocationFunctions* ifn, jlong threadStackSize,
2308                     int argc, char **argv,
2309                     int mode, char *what, int ret)
2310 {
2311     if (threadStackSize == 0) {
2312         /*
2313          * If the user hasn't specified a non-zero stack size ask the JVM for its default.
2314          * A returned 0 means 'use the system default' for a platform, e.g., Windows.
2315          * Note that HotSpot no longer supports JNI_VERSION_1_1 but it will
2316          * return its default stack size through the init args structure.
2317          */
2318         struct JDK1_1InitArgs args1_1;
2319         memset((void*)&args1_1, 0, sizeof(args1_1));
2320         args1_1.version = JNI_VERSION_1_1;
2321         ifn->GetDefaultJavaVMInitArgs(&args1_1);  /* ignore return value */
2322         if (args1_1.javaStackSize > 0) {
2323             threadStackSize = args1_1.javaStackSize;
2324         }
2325     }
2326 
2327     { /* Create a new thread to create JVM and invoke main method */
2328         JavaMainArgs args;
2329         int rslt;
2330 
2331         args.argc = argc;
2332         args.argv = argv;
2333         args.mode = mode;
2334         args.what = what;
2335         args.ifn = *ifn;
2336 
2337         rslt = CallJavaMainInNewThread(threadStackSize, (void*)&args);
2338         /* If the caller has deemed there is an error we
2339          * simply return that, otherwise we return the value of
2340          * the callee
2341          */
2342         return (ret != 0) ? ret : rslt;
2343     }
2344 }
2345 
2346 static void
2347 DumpState()
2348 {
2349     if (!JLI_IsTraceLauncher()) return ;
2350     printf("Launcher state:\n");
2351     printf("\tFirst application arg index: %d\n", JLI_GetAppArgIndex());
2352     printf("\tdebug:%s\n", (JLI_IsTraceLauncher() == JNI_TRUE) ? "on" : "off");
2353     printf("\tjavargs:%s\n", (_is_java_args == JNI_TRUE) ? "on" : "off");
2354     printf("\tprogram name:%s\n", GetProgramName());
2355     printf("\tlauncher name:%s\n", GetLauncherName());
2356     printf("\tjavaw:%s\n", (IsJavaw() == JNI_TRUE) ? "on" : "off");
2357     printf("\tfullversion:%s\n", GetFullVersion());
2358 }
2359 
2360 /*
2361  * A utility procedure to always print to stderr
2362  */
2363 JNIEXPORT void JNICALL
2364 JLI_ReportMessage(const char* fmt, ...)
2365 {
2366     va_list vl;
2367     va_start(vl, fmt);
2368     vfprintf(stderr, fmt, vl);
2369     fprintf(stderr, "\n");
2370     va_end(vl);
2371 }
2372 
2373 /*
2374  * A utility procedure to always print to stdout
2375  */
2376 void
2377 JLI_ShowMessage(const char* fmt, ...)
2378 {
2379     va_list vl;
2380     va_start(vl, fmt);
2381     vfprintf(stdout, fmt, vl);
2382     fprintf(stdout, "\n");
2383     va_end(vl);
2384 }