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