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