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