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