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