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