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