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