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