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