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         }
 777     }
 778 
 779     if (JLI_StrCCmp(str, "-Xmx") == 0) {
 780         jlong tmp;
 781         if (parse_size(str + 4, &tmp)) {
 782             maxHeapSize = tmp;
 783         }
 784     }
 785 
 786     if (JLI_StrCCmp(str, "-Xms") == 0) {
 787         jlong tmp;
 788         if (parse_size(str + 4, &tmp)) {
 789            initialHeapSize = tmp;
 790         }
 791     }
 792 }
 793 
 794 static void
 795 SetClassPath(const char *s)
 796 {
 797     char *def;
 798     const char *orig = s;
 799     static const char format[] = "-Djava.class.path=%s";
 800     /*
 801      * usually we should not get a null pointer, but there are cases where
 802      * we might just get one, in which case we simply ignore it, and let the
 803      * caller deal with it
 804      */
 805     if (s == NULL)
 806         return;
 807     s = JLI_WildcardExpandClasspath(s);
 808     if (sizeof(format) - 2 + JLI_StrLen(s) < JLI_StrLen(s))
 809         // s is became corrupted after expanding wildcards
 810         return;
 811     def = JLI_MemAlloc(sizeof(format)
 812                        - 2 /* strlen("%s") */
 813                        + JLI_StrLen(s));
 814     sprintf(def, format, s);
 815     AddOption(def, NULL);
 816     if (s != orig)
 817         JLI_MemFree((char *) s);
 818 }
 819 
 820 /*
 821  * The SelectVersion() routine ensures that an appropriate version of
 822  * the JRE is running.  The specification for the appropriate version
 823  * is obtained from either the manifest of a jar file (preferred) or
 824  * from command line options.
 825  * The routine also parses splash screen command line options and
 826  * passes on their values in private environment variables.
 827  */
 828 static void
 829 SelectVersion(int argc, char **argv, char **main_class)
 830 {
 831     char    *arg;
 832     char    **new_argv;
 833     char    **new_argp;
 834     char    *operand;
 835     char    *version = NULL;
 836     char    *jre = NULL;
 837     int     jarflag = 0;
 838     int     headlessflag = 0;
 839     int     restrict_search = -1;               /* -1 implies not known */
 840     manifest_info info;
 841     char    env_entry[MAXNAMELEN + 24] = ENV_ENTRY "=";
 842     char    *splash_file_name = NULL;
 843     char    *splash_jar_name = NULL;
 844     char    *env_in;
 845     int     res;
 846 
 847     /*
 848      * If the version has already been selected, set *main_class
 849      * with the value passed through the environment (if any) and
 850      * simply return.
 851      */
 852     if ((env_in = getenv(ENV_ENTRY)) != NULL) {
 853         if (*env_in != '\0')
 854             *main_class = JLI_StringDup(env_in);
 855         return;
 856     }
 857 
 858     /*
 859      * Scan through the arguments for options relevant to multiple JRE
 860      * support.  For reference, the command line syntax is defined as:
 861      *
 862      * SYNOPSIS
 863      *      java [options] class [argument...]
 864      *
 865      *      java [options] -jar file.jar [argument...]
 866      *
 867      * As the scan is performed, make a copy of the argument list with
 868      * the version specification options (new to 1.5) removed, so that
 869      * a version less than 1.5 can be exec'd.
 870      *
 871      * Note that due to the syntax of the native Windows interface
 872      * CreateProcess(), processing similar to the following exists in
 873      * the Windows platform specific routine ExecJRE (in java_md.c).
 874      * Changes here should be reproduced there.
 875      */
 876     new_argv = JLI_MemAlloc((argc + 1) * sizeof(char*));
 877     new_argv[0] = argv[0];
 878     new_argp = &new_argv[1];
 879     argc--;
 880     argv++;
 881     while ((arg = *argv) != 0 && *arg == '-') {
 882         if (JLI_StrCCmp(arg, "-version:") == 0) {
 883             version = arg + 9;
 884         } else if (JLI_StrCmp(arg, "-jre-restrict-search") == 0) {
 885             restrict_search = 1;
 886         } else if (JLI_StrCmp(arg, "-no-jre-restrict-search") == 0) {
 887             restrict_search = 0;
 888         } else {
 889             if (JLI_StrCmp(arg, "-jar") == 0)
 890                 jarflag = 1;
 891             /* deal with "unfortunate" classpath syntax */
 892             if ((JLI_StrCmp(arg, "-classpath") == 0 || JLI_StrCmp(arg, "-cp") == 0) &&
 893               (argc >= 2)) {
 894                 *new_argp++ = arg;
 895                 argc--;
 896                 argv++;
 897                 arg = *argv;
 898             }
 899 
 900             /*
 901              * Checking for headless toolkit option in the some way as AWT does:
 902              * "true" means true and any other value means false
 903              */
 904             if (JLI_StrCmp(arg, "-Djava.awt.headless=true") == 0) {
 905                 headlessflag = 1;
 906             } else if (JLI_StrCCmp(arg, "-Djava.awt.headless=") == 0) {
 907                 headlessflag = 0;
 908             } else if (JLI_StrCCmp(arg, "-splash:") == 0) {
 909                 splash_file_name = arg+8;
 910             }
 911             *new_argp++ = arg;
 912         }
 913         argc--;
 914         argv++;
 915     }
 916     if (argc <= 0) {    /* No operand? Possibly legit with -[full]version */
 917         operand = NULL;
 918     } else {
 919         argc--;
 920         *new_argp++ = operand = *argv++;
 921     }
 922     while (argc-- > 0)  /* Copy over [argument...] */
 923         *new_argp++ = *argv++;
 924     *new_argp = NULL;
 925 
 926     /*
 927      * If there is a jar file, read the manifest. If the jarfile can't be
 928      * read, the manifest can't be read from the jar file, or the manifest
 929      * is corrupt, issue the appropriate error messages and exit.
 930      *
 931      * Even if there isn't a jar file, construct a manifest_info structure
 932      * containing the command line information.  It's a convenient way to carry
 933      * this data around.
 934      */
 935     if (jarflag && operand) {
 936         if ((res = JLI_ParseManifest(operand, &info)) != 0) {
 937             if (res == -1)
 938                 JLI_ReportErrorMessage(JAR_ERROR2, operand);
 939             else
 940                 JLI_ReportErrorMessage(JAR_ERROR3, operand);
 941             exit(1);
 942         }
 943 
 944         /*
 945          * Command line splash screen option should have precedence
 946          * over the manifest, so the manifest data is used only if
 947          * splash_file_name has not been initialized above during command
 948          * line parsing
 949          */
 950         if (!headlessflag && !splash_file_name && info.splashscreen_image_file_name) {
 951             splash_file_name = info.splashscreen_image_file_name;
 952             splash_jar_name = operand;
 953         }
 954     } else {
 955         info.manifest_version = NULL;
 956         info.main_class = NULL;
 957         info.jre_version = NULL;
 958         info.jre_restrict_search = 0;
 959     }
 960 
 961     /*
 962      * Passing on splash screen info in environment variables
 963      */
 964     if (splash_file_name && !headlessflag) {
 965         char* splash_file_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_FILE_ENV_ENTRY "=")+JLI_StrLen(splash_file_name)+1);
 966         JLI_StrCpy(splash_file_entry, SPLASH_FILE_ENV_ENTRY "=");
 967         JLI_StrCat(splash_file_entry, splash_file_name);
 968         putenv(splash_file_entry);
 969     }
 970     if (splash_jar_name && !headlessflag) {
 971         char* splash_jar_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_JAR_ENV_ENTRY "=")+JLI_StrLen(splash_jar_name)+1);
 972         JLI_StrCpy(splash_jar_entry, SPLASH_JAR_ENV_ENTRY "=");
 973         JLI_StrCat(splash_jar_entry, splash_jar_name);
 974         putenv(splash_jar_entry);
 975     }
 976 
 977     /*
 978      * The JRE-Version and JRE-Restrict-Search values (if any) from the
 979      * manifest are overwritten by any specified on the command line.
 980      */
 981     if (version != NULL)
 982         info.jre_version = version;
 983     if (restrict_search != -1)
 984         info.jre_restrict_search = restrict_search;
 985 
 986     /*
 987      * "Valid" returns (other than unrecoverable errors) follow.  Set
 988      * main_class as a side-effect of this routine.
 989      */
 990     if (info.main_class != NULL)
 991         *main_class = JLI_StringDup(info.main_class);
 992 
 993     /*
 994      * If no version selection information is found either on the command
 995      * line or in the manifest, simply return.
 996      */
 997     if (info.jre_version == NULL) {
 998         JLI_FreeManifest();
 999         JLI_MemFree(new_argv);
1000         return;
1001     }
1002 
1003     /*
1004      * Check for correct syntax of the version specification (JSR 56).
1005      */
1006     if (!JLI_ValidVersionString(info.jre_version)) {
1007         JLI_ReportErrorMessage(SPC_ERROR1, info.jre_version);
1008         exit(1);
1009     }
1010 
1011     /*
1012      * Find the appropriate JVM on the system. Just to be as forgiving as
1013      * possible, if the standard algorithms don't locate an appropriate
1014      * jre, check to see if the one running will satisfy the requirements.
1015      * This can happen on systems which haven't been set-up for multiple
1016      * JRE support.
1017      */
1018     jre = LocateJRE(&info);
1019     JLI_TraceLauncher("JRE-Version = %s, JRE-Restrict-Search = %s Selected = %s\n",
1020         (info.jre_version?info.jre_version:"null"),
1021         (info.jre_restrict_search?"true":"false"), (jre?jre:"null"));
1022 
1023     if (jre == NULL) {
1024         if (JLI_AcceptableRelease(GetFullVersion(), info.jre_version)) {
1025             JLI_FreeManifest();
1026             JLI_MemFree(new_argv);
1027             return;
1028         } else {
1029             JLI_ReportErrorMessage(CFG_ERROR4, info.jre_version);
1030             exit(1);
1031         }
1032     }
1033 
1034     /*
1035      * If I'm not the chosen one, exec the chosen one.  Returning from
1036      * ExecJRE indicates that I am indeed the chosen one.
1037      *
1038      * The private environment variable _JAVA_VERSION_SET is used to
1039      * prevent the chosen one from re-reading the manifest file and
1040      * using the values found within to override the (potential) command
1041      * line flags stripped from argv (because the target may not
1042      * understand them).  Passing the MainClass value is an optimization
1043      * to avoid locating, expanding and parsing the manifest extra
1044      * times.
1045      */
1046     if (info.main_class != NULL) {
1047         if (JLI_StrLen(info.main_class) <= MAXNAMELEN) {
1048             (void)JLI_StrCat(env_entry, info.main_class);
1049         } else {
1050             JLI_ReportErrorMessage(CLS_ERROR5, MAXNAMELEN);
1051             exit(1);
1052         }
1053     }
1054     (void)putenv(env_entry);
1055     ExecJRE(jre, new_argv);
1056     JLI_FreeManifest();
1057     JLI_MemFree(new_argv);
1058     return;
1059 }
1060 
1061 /*
1062  * Parses command line arguments.  Returns JNI_FALSE if launcher
1063  * should exit without starting vm, returns JNI_TRUE if vm needs
1064  * to be started to process given options.  *pret (the launcher
1065  * process return value) is set to 0 for a normal exit.
1066  */
1067 static jboolean
1068 ParseArguments(int *pargc, char ***pargv,
1069                int *pmode, char **pwhat,
1070                int *pret, const char *jrepath)
1071 {
1072     int argc = *pargc;
1073     char **argv = *pargv;
1074     int mode = LM_UNKNOWN;
1075     char *arg;
1076 
1077     *pret = 0;
1078 
1079     while ((arg = *argv) != 0 && *arg == '-') {
1080         argv++; --argc;
1081         if (JLI_StrCmp(arg, "-classpath") == 0 || JLI_StrCmp(arg, "-cp") == 0) {
1082             ARG_CHECK (argc, ARG_ERROR1, arg);
1083             SetClassPath(*argv);
1084             mode = LM_CLASS;
1085             argv++; --argc;
1086         } else if (JLI_StrCmp(arg, "-jar") == 0) {
1087             ARG_CHECK (argc, ARG_ERROR2, arg);
1088             mode = LM_JAR;
1089         } else if (JLI_StrCmp(arg, "-help") == 0 ||
1090                    JLI_StrCmp(arg, "-h") == 0 ||
1091                    JLI_StrCmp(arg, "-?") == 0) {
1092             printUsage = JNI_TRUE;
1093             return JNI_TRUE;
1094         } else if (JLI_StrCmp(arg, "-version") == 0) {
1095             printVersion = JNI_TRUE;
1096             return JNI_TRUE;
1097         } else if (JLI_StrCmp(arg, "-showversion") == 0) {
1098             showVersion = JNI_TRUE;
1099         } else if (JLI_StrCmp(arg, "-X") == 0) {
1100             printXUsage = JNI_TRUE;
1101             return JNI_TRUE;
1102 /*
1103  * The following case checks for -XshowSettings OR -XshowSetting:SUBOPT.
1104  * In the latter case, any SUBOPT value not recognized will default to "all"
1105  */
1106         } else if (JLI_StrCmp(arg, "-XshowSettings") == 0 ||
1107                 JLI_StrCCmp(arg, "-XshowSettings:") == 0) {
1108             showSettings = arg;
1109         } else if (JLI_StrCmp(arg, "-Xdiag") == 0) {
1110             AddOption("-Dsun.java.launcher.diag=true", NULL);
1111 /*
1112  * The following case provide backward compatibility with old-style
1113  * command line options.
1114  */
1115         } else if (JLI_StrCmp(arg, "-fullversion") == 0) {
1116             JLI_ReportMessage("%s full version \"%s\"", _launcher_name, GetFullVersion());
1117             return JNI_FALSE;
1118         } else if (JLI_StrCmp(arg, "-verbosegc") == 0) {
1119             AddOption("-verbose:gc", NULL);
1120         } else if (JLI_StrCmp(arg, "-t") == 0) {
1121             AddOption("-Xt", NULL);
1122         } else if (JLI_StrCmp(arg, "-tm") == 0) {
1123             AddOption("-Xtm", NULL);
1124         } else if (JLI_StrCmp(arg, "-debug") == 0) {
1125             AddOption("-Xdebug", NULL);
1126         } else if (JLI_StrCmp(arg, "-noclassgc") == 0) {
1127             AddOption("-Xnoclassgc", NULL);
1128         } else if (JLI_StrCmp(arg, "-Xfuture") == 0) {
1129             AddOption("-Xverify:all", NULL);
1130         } else if (JLI_StrCmp(arg, "-verify") == 0) {
1131             AddOption("-Xverify:all", NULL);
1132         } else if (JLI_StrCmp(arg, "-verifyremote") == 0) {
1133             AddOption("-Xverify:remote", NULL);
1134         } else if (JLI_StrCmp(arg, "-noverify") == 0) {
1135             AddOption("-Xverify:none", NULL);
1136         } else if (JLI_StrCCmp(arg, "-prof") == 0) {
1137             char *p = arg + 5;
1138             char *tmp = JLI_MemAlloc(JLI_StrLen(arg) + 50);
1139             if (*p) {
1140                 sprintf(tmp, "-Xrunhprof:cpu=old,file=%s", p + 1);
1141             } else {
1142                 sprintf(tmp, "-Xrunhprof:cpu=old,file=java.prof");
1143             }
1144             AddOption(tmp, NULL);
1145         } else if (JLI_StrCCmp(arg, "-ss") == 0 ||
1146                    JLI_StrCCmp(arg, "-oss") == 0 ||
1147                    JLI_StrCCmp(arg, "-ms") == 0 ||
1148                    JLI_StrCCmp(arg, "-mx") == 0) {
1149             char *tmp = JLI_MemAlloc(JLI_StrLen(arg) + 6);
1150             sprintf(tmp, "-X%s", arg + 1); /* skip '-' */
1151             AddOption(tmp, NULL);
1152         } else if (JLI_StrCmp(arg, "-checksource") == 0 ||
1153                    JLI_StrCmp(arg, "-cs") == 0 ||
1154                    JLI_StrCmp(arg, "-noasyncgc") == 0) {
1155             /* No longer supported */
1156             JLI_ReportErrorMessage(ARG_WARN, arg);
1157         } else if (JLI_StrCCmp(arg, "-version:") == 0 ||
1158                    JLI_StrCmp(arg, "-no-jre-restrict-search") == 0 ||
1159                    JLI_StrCmp(arg, "-jre-restrict-search") == 0 ||
1160                    JLI_StrCCmp(arg, "-splash:") == 0) {
1161             ; /* Ignore machine independent options already handled */
1162         } else if (ProcessPlatformOption(arg)) {
1163             ; /* Processing of platform dependent options */
1164         } else if (RemovableOption(arg)) {
1165             ; /* Do not pass option to vm. */
1166         } else {
1167             AddOption(arg, NULL);
1168         }
1169     }
1170 
1171     if (--argc >= 0) {
1172         *pwhat = *argv++;
1173     }
1174 
1175     if (*pwhat == NULL) {
1176         *pret = 1;
1177     } else if (mode == LM_UNKNOWN) {
1178         /* default to LM_CLASS if -jar and -cp option are
1179          * not specified */
1180         mode = LM_CLASS;
1181     }
1182 
1183     if (argc >= 0) {
1184         *pargc = argc;
1185         *pargv = argv;
1186     }
1187 
1188     *pmode = mode;
1189 
1190     return JNI_TRUE;
1191 }
1192 
1193 /*
1194  * Initializes the Java Virtual Machine. Also frees options array when
1195  * finished.
1196  */
1197 static jboolean
1198 InitializeJVM(JavaVM **pvm, JNIEnv **penv, InvocationFunctions *ifn)
1199 {
1200     JavaVMInitArgs args;
1201     jint r;
1202 
1203     memset(&args, 0, sizeof(args));
1204     args.version  = JNI_VERSION_1_2;
1205     args.nOptions = numOptions;
1206     args.options  = options;
1207     args.ignoreUnrecognized = JNI_FALSE;
1208 
1209     if (JLI_IsTraceLauncher()) {
1210         int i = 0;
1211         printf("JavaVM args:\n    ");
1212         printf("version 0x%08lx, ", (long)args.version);
1213         printf("ignoreUnrecognized is %s, ",
1214                args.ignoreUnrecognized ? "JNI_TRUE" : "JNI_FALSE");
1215         printf("nOptions is %ld\n", (long)args.nOptions);
1216         for (i = 0; i < numOptions; i++)
1217             printf("    option[%2d] = '%s'\n",
1218                    i, args.options[i].optionString);
1219     }
1220 
1221     r = ifn->CreateJavaVM(pvm, (void **)penv, &args);
1222     JLI_MemFree(options);
1223     return r == JNI_OK;
1224 }
1225 
1226 static jclass helperClass = NULL;
1227 
1228 jclass
1229 GetLauncherHelperClass(JNIEnv *env)
1230 {
1231     if (helperClass == NULL) {
1232         NULL_CHECK0(helperClass = FindBootStrapClass(env,
1233                 "sun/launcher/LauncherHelper"));
1234     }
1235     return helperClass;
1236 }
1237 
1238 static jmethodID makePlatformStringMID = NULL;
1239 /*
1240  * Returns a new Java string object for the specified platform string.
1241  */
1242 static jstring
1243 NewPlatformString(JNIEnv *env, char *s)
1244 {
1245     int len = (int)JLI_StrLen(s);
1246     jbyteArray ary;
1247     jclass cls = GetLauncherHelperClass(env);
1248     NULL_CHECK0(cls);
1249     if (s == NULL)
1250         return 0;
1251 
1252     ary = (*env)->NewByteArray(env, len);
1253     if (ary != 0) {
1254         jstring str = 0;
1255         (*env)->SetByteArrayRegion(env, ary, 0, len, (jbyte *)s);
1256         if (!(*env)->ExceptionOccurred(env)) {
1257             if (makePlatformStringMID == NULL) {
1258                 NULL_CHECK0(makePlatformStringMID = (*env)->GetStaticMethodID(env,
1259                         cls, "makePlatformString", "(Z[B)Ljava/lang/String;"));
1260             }
1261             str = (*env)->CallStaticObjectMethod(env, cls,
1262                     makePlatformStringMID, USE_STDERR, ary);
1263             (*env)->DeleteLocalRef(env, ary);
1264             return str;
1265         }
1266     }
1267     return 0;
1268 }
1269 
1270 /*
1271  * Returns a new array of Java string objects for the specified
1272  * array of platform strings.
1273  */
1274 jobjectArray
1275 NewPlatformStringArray(JNIEnv *env, char **strv, int strc)
1276 {
1277     jarray cls;
1278     jarray ary;
1279     int i;
1280 
1281     NULL_CHECK0(cls = FindBootStrapClass(env, "java/lang/String"));
1282     NULL_CHECK0(ary = (*env)->NewObjectArray(env, strc, cls, 0));
1283     for (i = 0; i < strc; i++) {
1284         jstring str = NewPlatformString(env, *strv++);
1285         NULL_CHECK0(str);
1286         (*env)->SetObjectArrayElement(env, ary, i, str);
1287         (*env)->DeleteLocalRef(env, str);
1288     }
1289     return ary;
1290 }
1291 
1292 /*
1293  * Loads a class and verifies that the main class is present and it is ok to
1294  * call it for more details refer to the java implementation.
1295  */
1296 static jclass
1297 LoadMainClass(JNIEnv *env, int mode, char *name)
1298 {
1299     jmethodID mid;
1300     jstring str;
1301     jobject result;
1302     jlong start, end;
1303     jclass cls = GetLauncherHelperClass(env);
1304     NULL_CHECK0(cls);
1305     if (JLI_IsTraceLauncher()) {
1306         start = CounterGet();
1307     }
1308     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1309                 "checkAndLoadMain",
1310                 "(ZILjava/lang/String;)Ljava/lang/Class;"));
1311 
1312     NULL_CHECK0(str = NewPlatformString(env, name));
1313     NULL_CHECK0(result = (*env)->CallStaticObjectMethod(env, cls, mid,
1314                                                         USE_STDERR, mode, str));
1315 
1316     if (JLI_IsTraceLauncher()) {
1317         end   = CounterGet();
1318         printf("%ld micro seconds to load main class\n",
1319                (long)(jint)Counter2Micros(end-start));
1320         printf("----%s----\n", JLDEBUG_ENV_ENTRY);
1321     }
1322 
1323     return (jclass)result;
1324 }
1325 
1326 static jclass
1327 GetApplicationClass(JNIEnv *env)
1328 {
1329     jmethodID mid;
1330     jclass cls = GetLauncherHelperClass(env);
1331     NULL_CHECK0(cls);
1332     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1333                 "getApplicationClass",
1334                 "()Ljava/lang/Class;"));
1335 
1336     return (*env)->CallStaticObjectMethod(env, cls, mid);
1337 }
1338 
1339 /*
1340  * For tools, convert command line args thus:
1341  *   javac -cp foo:foo/"*" -J-ms32m ...
1342  *   java -ms32m -cp JLI_WildcardExpandClasspath(foo:foo/"*") ...
1343  *
1344  * Takes 4 parameters, and returns the populated arguments
1345  */
1346 static void
1347 TranslateApplicationArgs(int jargc, const char **jargv, int *pargc, char ***pargv)
1348 {
1349     int argc = *pargc;
1350     char **argv = *pargv;
1351     int nargc = argc + jargc;
1352     char **nargv = JLI_MemAlloc((nargc + 1) * sizeof(char *));
1353     int i;
1354 
1355     *pargc = nargc;
1356     *pargv = nargv;
1357 
1358     /* Copy the VM arguments (i.e. prefixed with -J) */
1359     for (i = 0; i < jargc; i++) {
1360         const char *arg = jargv[i];
1361         if (arg[0] == '-' && arg[1] == 'J') {
1362             *nargv++ = ((arg + 2) == NULL) ? NULL : JLI_StringDup(arg + 2);
1363         }
1364     }
1365 
1366     for (i = 0; i < argc; i++) {
1367         char *arg = argv[i];
1368         if (arg[0] == '-' && arg[1] == 'J') {
1369             if (arg[2] == '\0') {
1370                 JLI_ReportErrorMessage(ARG_ERROR3);
1371                 exit(1);
1372             }
1373             *nargv++ = arg + 2;
1374         }
1375     }
1376 
1377     /* Copy the rest of the arguments */
1378     for (i = 0; i < jargc ; i++) {
1379         const char *arg = jargv[i];
1380         if (arg[0] != '-' || arg[1] != 'J') {
1381             *nargv++ = (arg == NULL) ? NULL : JLI_StringDup(arg);
1382         }
1383     }
1384     for (i = 0; i < argc; i++) {
1385         char *arg = argv[i];
1386         if (arg[0] == '-') {
1387             if (arg[1] == 'J')
1388                 continue;
1389             if (IsWildCardEnabled() && arg[1] == 'c'
1390                 && (JLI_StrCmp(arg, "-cp") == 0 ||
1391                     JLI_StrCmp(arg, "-classpath") == 0)
1392                 && i < argc - 1) {
1393                 *nargv++ = arg;
1394                 *nargv++ = (char *) JLI_WildcardExpandClasspath(argv[i+1]);
1395                 i++;
1396                 continue;
1397             }
1398         }
1399         *nargv++ = arg;
1400     }
1401     *nargv = 0;
1402 }
1403 
1404 /*
1405  * For our tools, we try to add 3 VM options:
1406  *      -Denv.class.path=<envcp>
1407  *      -Dapplication.home=<apphome>
1408  *      -Djava.class.path=<appcp>
1409  * <envcp>   is the user's setting of CLASSPATH -- for instance the user
1410  *           tells javac where to find binary classes through this environment
1411  *           variable.  Notice that users will be able to compile against our
1412  *           tools classes (sun.tools.javac.Main) only if they explicitly add
1413  *           tools.jar to CLASSPATH.
1414  * <apphome> is the directory where the application is installed.
1415  * <appcp>   is the classpath to where our apps' classfiles are.
1416  */
1417 static jboolean
1418 AddApplicationOptions(int cpathc, const char **cpathv)
1419 {
1420     char *envcp, *appcp, *apphome;
1421     char home[MAXPATHLEN]; /* application home */
1422     char separator[] = { PATH_SEPARATOR, '\0' };
1423     int size, i;
1424 
1425     {
1426         const char *s = getenv("CLASSPATH");
1427         if (s) {
1428             s = (char *) JLI_WildcardExpandClasspath(s);
1429             /* 40 for -Denv.class.path= */
1430             if (JLI_StrLen(s) + 40 > JLI_StrLen(s)) { // Safeguard from overflow
1431                 envcp = (char *)JLI_MemAlloc(JLI_StrLen(s) + 40);
1432                 sprintf(envcp, "-Denv.class.path=%s", s);
1433                 AddOption(envcp, NULL);
1434             }
1435         }
1436     }
1437 
1438     if (!GetApplicationHome(home, sizeof(home))) {
1439         JLI_ReportErrorMessage(CFG_ERROR5);
1440         return JNI_FALSE;
1441     }
1442 
1443     /* 40 for '-Dapplication.home=' */
1444     apphome = (char *)JLI_MemAlloc(JLI_StrLen(home) + 40);
1445     sprintf(apphome, "-Dapplication.home=%s", home);
1446     AddOption(apphome, NULL);
1447 
1448     /* How big is the application's classpath? */
1449     size = 40;                                 /* 40: "-Djava.class.path=" */
1450     for (i = 0; i < cpathc; i++) {
1451         size += (int)JLI_StrLen(home) + (int)JLI_StrLen(cpathv[i]) + 1; /* 1: separator */
1452     }
1453     appcp = (char *)JLI_MemAlloc(size + 1);
1454     JLI_StrCpy(appcp, "-Djava.class.path=");
1455     for (i = 0; i < cpathc; i++) {
1456         JLI_StrCat(appcp, home);                        /* c:\program files\myapp */
1457         JLI_StrCat(appcp, cpathv[i]);           /* \lib\myapp.jar         */
1458         JLI_StrCat(appcp, separator);           /* ;                      */
1459     }
1460     appcp[JLI_StrLen(appcp)-1] = '\0';  /* remove trailing path separator */
1461     AddOption(appcp, NULL);
1462     return JNI_TRUE;
1463 }
1464 
1465 /*
1466  * inject the -Dsun.java.command pseudo property into the args structure
1467  * this pseudo property is used in the HotSpot VM to expose the
1468  * Java class name and arguments to the main method to the VM. The
1469  * HotSpot VM uses this pseudo property to store the Java class name
1470  * (or jar file name) and the arguments to the class's main method
1471  * to the instrumentation memory region. The sun.java.command pseudo
1472  * property is not exported by HotSpot to the Java layer.
1473  */
1474 void
1475 SetJavaCommandLineProp(char *what, int argc, char **argv)
1476 {
1477 
1478     int i = 0;
1479     size_t len = 0;
1480     char* javaCommand = NULL;
1481     char* dashDstr = "-Dsun.java.command=";
1482 
1483     if (what == NULL) {
1484         /* unexpected, one of these should be set. just return without
1485          * setting the property
1486          */
1487         return;
1488     }
1489 
1490     /* determine the amount of memory to allocate assuming
1491      * the individual components will be space separated
1492      */
1493     len = JLI_StrLen(what);
1494     for (i = 0; i < argc; i++) {
1495         len += JLI_StrLen(argv[i]) + 1;
1496     }
1497 
1498     /* allocate the memory */
1499     javaCommand = (char*) JLI_MemAlloc(len + JLI_StrLen(dashDstr) + 1);
1500 
1501     /* build the -D string */
1502     *javaCommand = '\0';
1503     JLI_StrCat(javaCommand, dashDstr);
1504     JLI_StrCat(javaCommand, what);
1505 
1506     for (i = 0; i < argc; i++) {
1507         /* the components of the string are space separated. In
1508          * the case of embedded white space, the relationship of
1509          * the white space separated components to their true
1510          * positional arguments will be ambiguous. This issue may
1511          * be addressed in a future release.
1512          */
1513         JLI_StrCat(javaCommand, " ");
1514         JLI_StrCat(javaCommand, argv[i]);
1515     }
1516 
1517     AddOption(javaCommand, NULL);
1518 }
1519 
1520 /*
1521  * JVM would like to know if it's created by a standard Sun launcher, or by
1522  * user native application, the following property indicates the former.
1523  */
1524 void
1525 SetJavaLauncherProp() {
1526   AddOption("-Dsun.java.launcher=SUN_STANDARD", NULL);
1527 }
1528 
1529 /*
1530  * Prints the version information from the java.version and other properties.
1531  */
1532 static void
1533 PrintJavaVersion(JNIEnv *env, jboolean extraLF)
1534 {
1535     jclass ver;
1536     jmethodID print;
1537 
1538     NULL_CHECK(ver = FindBootStrapClass(env, "sun/misc/Version"));
1539     NULL_CHECK(print = (*env)->GetStaticMethodID(env,
1540                                                  ver,
1541                                                  (extraLF == JNI_TRUE) ? "println" : "print",
1542                                                  "()V"
1543                                                  )
1544               );
1545 
1546     (*env)->CallStaticVoidMethod(env, ver, print);
1547 }
1548 
1549 /*
1550  * Prints all the Java settings, see the java implementation for more details.
1551  */
1552 static void
1553 ShowSettings(JNIEnv *env, char *optString)
1554 {
1555     jmethodID showSettingsID;
1556     jstring joptString;
1557     jclass cls = GetLauncherHelperClass(env);
1558     NULL_CHECK(cls);
1559     NULL_CHECK(showSettingsID = (*env)->GetStaticMethodID(env, cls,
1560             "showSettings", "(ZLjava/lang/String;JJJZ)V"));
1561     NULL_CHECK(joptString = (*env)->NewStringUTF(env, optString));
1562     (*env)->CallStaticVoidMethod(env, cls, showSettingsID,
1563                                  USE_STDERR,
1564                                  joptString,
1565                                  (jlong)initialHeapSize,
1566                                  (jlong)maxHeapSize,
1567                                  (jlong)threadStackSize,
1568                                  ServerClassMachine());
1569 }
1570 
1571 /*
1572  * Prints default usage or the Xusage message, see sun.launcher.LauncherHelper.java
1573  */
1574 static void
1575 PrintUsage(JNIEnv* env, jboolean doXUsage)
1576 {
1577   jmethodID initHelp, vmSelect, vmSynonym, vmErgo, printHelp, printXUsageMessage;
1578   jstring jprogname, vm1, vm2;
1579   int i;
1580   jclass cls = GetLauncherHelperClass(env);
1581   NULL_CHECK(cls);
1582   if (doXUsage) {
1583     NULL_CHECK(printXUsageMessage = (*env)->GetStaticMethodID(env, cls,
1584                                         "printXUsageMessage", "(Z)V"));
1585     (*env)->CallStaticVoidMethod(env, cls, printXUsageMessage, USE_STDERR);
1586   } else {
1587     NULL_CHECK(initHelp = (*env)->GetStaticMethodID(env, cls,
1588                                         "initHelpMessage", "(Ljava/lang/String;)V"));
1589 
1590     NULL_CHECK(vmSelect = (*env)->GetStaticMethodID(env, cls, "appendVmSelectMessage",
1591                                         "(Ljava/lang/String;Ljava/lang/String;)V"));
1592 
1593     NULL_CHECK(vmSynonym = (*env)->GetStaticMethodID(env, cls,
1594                                         "appendVmSynonymMessage",
1595                                         "(Ljava/lang/String;Ljava/lang/String;)V"));
1596     NULL_CHECK(vmErgo = (*env)->GetStaticMethodID(env, cls,
1597                                         "appendVmErgoMessage", "(ZLjava/lang/String;)V"));
1598 
1599     NULL_CHECK(printHelp = (*env)->GetStaticMethodID(env, cls,
1600                                         "printHelpMessage", "(Z)V"));
1601 
1602     NULL_CHECK(jprogname = (*env)->NewStringUTF(env, _program_name));
1603 
1604     /* Initialize the usage message with the usual preamble */
1605     (*env)->CallStaticVoidMethod(env, cls, initHelp, jprogname);
1606     CHECK_EXCEPTION_RETURN();
1607 
1608 
1609     /* Assemble the other variant part of the usage */
1610     if ((knownVMs[0].flag == VM_KNOWN) ||
1611         (knownVMs[0].flag == VM_IF_SERVER_CLASS)) {
1612       NULL_CHECK(vm1 = (*env)->NewStringUTF(env, knownVMs[0].name));
1613       NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[0].name+1));
1614       (*env)->CallStaticVoidMethod(env, cls, vmSelect, vm1, vm2);
1615       CHECK_EXCEPTION_RETURN();
1616     }
1617     for (i=1; i<knownVMsCount; i++) {
1618       if (knownVMs[i].flag == VM_KNOWN) {
1619         NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
1620         NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].name+1));
1621         (*env)->CallStaticVoidMethod(env, cls, vmSelect, vm1, vm2);
1622         CHECK_EXCEPTION_RETURN();
1623       }
1624     }
1625     for (i=1; i<knownVMsCount; i++) {
1626       if (knownVMs[i].flag == VM_ALIASED_TO) {
1627         NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
1628         NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].alias+1));
1629         (*env)->CallStaticVoidMethod(env, cls, vmSynonym, vm1, vm2);
1630         CHECK_EXCEPTION_RETURN();
1631       }
1632     }
1633 
1634     /* The first known VM is the default */
1635     {
1636       jboolean isServerClassMachine = ServerClassMachine();
1637 
1638       const char* defaultVM  =  knownVMs[0].name+1;
1639       if ((knownVMs[0].flag == VM_IF_SERVER_CLASS) && isServerClassMachine) {
1640         defaultVM = knownVMs[0].server_class+1;
1641       }
1642 
1643       NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, defaultVM));
1644       (*env)->CallStaticVoidMethod(env, cls, vmErgo, isServerClassMachine,  vm1);
1645       CHECK_EXCEPTION_RETURN();
1646     }
1647 
1648     /* Complete the usage message and print to stderr*/
1649     (*env)->CallStaticVoidMethod(env, cls, printHelp, USE_STDERR);
1650   }
1651   return;
1652 }
1653 
1654 /*
1655  * Read the jvm.cfg file and fill the knownJVMs[] array.
1656  *
1657  * The functionality of the jvm.cfg file is subject to change without
1658  * notice and the mechanism will be removed in the future.
1659  *
1660  * The lexical structure of the jvm.cfg file is as follows:
1661  *
1662  *     jvmcfg         :=  { vmLine }
1663  *     vmLine         :=  knownLine
1664  *                    |   aliasLine
1665  *                    |   warnLine
1666  *                    |   ignoreLine
1667  *                    |   errorLine
1668  *                    |   predicateLine
1669  *                    |   commentLine
1670  *     knownLine      :=  flag  "KNOWN"                  EOL
1671  *     warnLine       :=  flag  "WARN"                   EOL
1672  *     ignoreLine     :=  flag  "IGNORE"                 EOL
1673  *     errorLine      :=  flag  "ERROR"                  EOL
1674  *     aliasLine      :=  flag  "ALIASED_TO"       flag  EOL
1675  *     predicateLine  :=  flag  "IF_SERVER_CLASS"  flag  EOL
1676  *     commentLine    :=  "#" text                       EOL
1677  *     flag           :=  "-" identifier
1678  *
1679  * The semantics are that when someone specifies a flag on the command line:
1680  * - if the flag appears on a knownLine, then the identifier is used as
1681  *   the name of the directory holding the JVM library (the name of the JVM).
1682  * - if the flag appears as the first flag on an aliasLine, the identifier
1683  *   of the second flag is used as the name of the JVM.
1684  * - if the flag appears on a warnLine, the identifier is used as the
1685  *   name of the JVM, but a warning is generated.
1686  * - if the flag appears on an ignoreLine, the identifier is recognized as the
1687  *   name of a JVM, but the identifier is ignored and the default vm used
1688  * - if the flag appears on an errorLine, an error is generated.
1689  * - if the flag appears as the first flag on a predicateLine, and
1690  *   the machine on which you are running passes the predicate indicated,
1691  *   then the identifier of the second flag is used as the name of the JVM,
1692  *   otherwise the identifier of the first flag is used as the name of the JVM.
1693  * If no flag is given on the command line, the first vmLine of the jvm.cfg
1694  * file determines the name of the JVM.
1695  * PredicateLines are only interpreted on first vmLine of a jvm.cfg file,
1696  * since they only make sense if someone hasn't specified the name of the
1697  * JVM on the command line.
1698  *
1699  * The intent of the jvm.cfg file is to allow several JVM libraries to
1700  * be installed in different subdirectories of a single JRE installation,
1701  * for space-savings and convenience in testing.
1702  * The intent is explicitly not to provide a full aliasing or predicate
1703  * mechanism.
1704  */
1705 jint
1706 ReadKnownVMs(const char *jvmCfgName, jboolean speculative)
1707 {
1708     FILE *jvmCfg;
1709     char line[MAXPATHLEN+20];
1710     int cnt = 0;
1711     int lineno = 0;
1712     jlong start, end;
1713     int vmType;
1714     char *tmpPtr;
1715     char *altVMName = NULL;
1716     char *serverClassVMName = NULL;
1717     static char *whiteSpace = " \t";
1718     if (JLI_IsTraceLauncher()) {
1719         start = CounterGet();
1720     }
1721 
1722     jvmCfg = fopen(jvmCfgName, "r");
1723     if (jvmCfg == NULL) {
1724       if (!speculative) {
1725         JLI_ReportErrorMessage(CFG_ERROR6, jvmCfgName);
1726         exit(1);
1727       } else {
1728         return -1;
1729       }
1730     }
1731     while (fgets(line, sizeof(line), jvmCfg) != NULL) {
1732         vmType = VM_UNKNOWN;
1733         lineno++;
1734         if (line[0] == '#')
1735             continue;
1736         if (line[0] != '-') {
1737             JLI_ReportErrorMessage(CFG_WARN2, lineno, jvmCfgName);
1738         }
1739         if (cnt >= knownVMsLimit) {
1740             GrowKnownVMs(cnt);
1741         }
1742         line[JLI_StrLen(line)-1] = '\0'; /* remove trailing newline */
1743         tmpPtr = line + JLI_StrCSpn(line, whiteSpace);
1744         if (*tmpPtr == 0) {
1745             JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
1746         } else {
1747             /* Null-terminate this string for JLI_StringDup below */
1748             *tmpPtr++ = 0;
1749             tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
1750             if (*tmpPtr == 0) {
1751                 JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
1752             } else {
1753                 if (!JLI_StrCCmp(tmpPtr, "KNOWN")) {
1754                     vmType = VM_KNOWN;
1755                 } else if (!JLI_StrCCmp(tmpPtr, "ALIASED_TO")) {
1756                     tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
1757                     if (*tmpPtr != 0) {
1758                         tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
1759                     }
1760                     if (*tmpPtr == 0) {
1761                         JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
1762                     } else {
1763                         /* Null terminate altVMName */
1764                         altVMName = tmpPtr;
1765                         tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
1766                         *tmpPtr = 0;
1767                         vmType = VM_ALIASED_TO;
1768                     }
1769                 } else if (!JLI_StrCCmp(tmpPtr, "WARN")) {
1770                     vmType = VM_WARN;
1771                 } else if (!JLI_StrCCmp(tmpPtr, "IGNORE")) {
1772                     vmType = VM_IGNORE;
1773                 } else if (!JLI_StrCCmp(tmpPtr, "ERROR")) {
1774                     vmType = VM_ERROR;
1775                 } else if (!JLI_StrCCmp(tmpPtr, "IF_SERVER_CLASS")) {
1776                     tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
1777                     if (*tmpPtr != 0) {
1778                         tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
1779                     }
1780                     if (*tmpPtr == 0) {
1781                         JLI_ReportErrorMessage(CFG_WARN4, lineno, jvmCfgName);
1782                     } else {
1783                         /* Null terminate server class VM name */
1784                         serverClassVMName = tmpPtr;
1785                         tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
1786                         *tmpPtr = 0;
1787                         vmType = VM_IF_SERVER_CLASS;
1788                     }
1789                 } else {
1790                     JLI_ReportErrorMessage(CFG_WARN5, lineno, &jvmCfgName[0]);
1791                     vmType = VM_KNOWN;
1792                 }
1793             }
1794         }
1795 
1796         JLI_TraceLauncher("jvm.cfg[%d] = ->%s<-\n", cnt, line);
1797         if (vmType != VM_UNKNOWN) {
1798             knownVMs[cnt].name = JLI_StringDup(line);
1799             knownVMs[cnt].flag = vmType;
1800             switch (vmType) {
1801             default:
1802                 break;
1803             case VM_ALIASED_TO:
1804                 knownVMs[cnt].alias = JLI_StringDup(altVMName);
1805                 JLI_TraceLauncher("    name: %s  vmType: %s  alias: %s\n",
1806                    knownVMs[cnt].name, "VM_ALIASED_TO", knownVMs[cnt].alias);
1807                 break;
1808             case VM_IF_SERVER_CLASS:
1809                 knownVMs[cnt].server_class = JLI_StringDup(serverClassVMName);
1810                 JLI_TraceLauncher("    name: %s  vmType: %s  server_class: %s\n",
1811                     knownVMs[cnt].name, "VM_IF_SERVER_CLASS", knownVMs[cnt].server_class);
1812                 break;
1813             }
1814             cnt++;
1815         }
1816     }
1817     fclose(jvmCfg);
1818     knownVMsCount = cnt;
1819 
1820     if (JLI_IsTraceLauncher()) {
1821         end   = CounterGet();
1822         printf("%ld micro seconds to parse jvm.cfg\n",
1823                (long)(jint)Counter2Micros(end-start));
1824     }
1825 
1826     return cnt;
1827 }
1828 
1829 
1830 static void
1831 GrowKnownVMs(int minimum)
1832 {
1833     struct vmdesc* newKnownVMs;
1834     int newMax;
1835 
1836     newMax = (knownVMsLimit == 0 ? INIT_MAX_KNOWN_VMS : (2 * knownVMsLimit));
1837     if (newMax <= minimum) {
1838         newMax = minimum;
1839     }
1840     newKnownVMs = (struct vmdesc*) JLI_MemAlloc(newMax * sizeof(struct vmdesc));
1841     if (knownVMs != NULL) {
1842         memcpy(newKnownVMs, knownVMs, knownVMsLimit * sizeof(struct vmdesc));
1843     }
1844     JLI_MemFree(knownVMs);
1845     knownVMs = newKnownVMs;
1846     knownVMsLimit = newMax;
1847 }
1848 
1849 
1850 /* Returns index of VM or -1 if not found */
1851 static int
1852 KnownVMIndex(const char* name)
1853 {
1854     int i;
1855     if (JLI_StrCCmp(name, "-J") == 0) name += 2;
1856     for (i = 0; i < knownVMsCount; i++) {
1857         if (!JLI_StrCmp(name, knownVMs[i].name)) {
1858             return i;
1859         }
1860     }
1861     return -1;
1862 }
1863 
1864 static void
1865 FreeKnownVMs()
1866 {
1867     int i;
1868     for (i = 0; i < knownVMsCount; i++) {
1869         JLI_MemFree(knownVMs[i].name);
1870         knownVMs[i].name = NULL;
1871     }
1872     JLI_MemFree(knownVMs);
1873 }
1874 
1875 /*
1876  * Displays the splash screen according to the jar file name
1877  * and image file names stored in environment variables
1878  */
1879 void
1880 ShowSplashScreen()
1881 {
1882     const char *jar_name = getenv(SPLASH_JAR_ENV_ENTRY);
1883     const char *file_name = getenv(SPLASH_FILE_ENV_ENTRY);
1884     int data_size;
1885     void *image_data = NULL;
1886     float scale_factor = 1;
1887     char *scaled_splash_name = NULL;
1888 
1889     if (file_name == NULL){
1890         return;
1891     }
1892 
1893     scaled_splash_name = DoSplashGetScaledImageName(
1894                         jar_name, file_name, &scale_factor);
1895     if (jar_name) {
1896 
1897         if (scaled_splash_name) {
1898             image_data = JLI_JarUnpackFile(
1899                     jar_name, scaled_splash_name, &data_size);
1900         }
1901 
1902         if (!image_data) {
1903             scale_factor = 1;
1904             image_data = JLI_JarUnpackFile(
1905                             jar_name, file_name, &data_size);
1906         }
1907         if (image_data) {
1908             DoSplashInit();
1909             DoSplashSetScaleFactor(scale_factor);
1910             DoSplashLoadMemory(image_data, data_size);
1911             JLI_MemFree(image_data);
1912         }
1913     } else {
1914         DoSplashInit();
1915         if (scaled_splash_name) {
1916             DoSplashSetScaleFactor(scale_factor);
1917             DoSplashLoadFile(scaled_splash_name);
1918         } else {
1919             DoSplashLoadFile(file_name);
1920         }
1921     }
1922 
1923     if (scaled_splash_name) {
1924         JLI_MemFree(scaled_splash_name);
1925     }
1926 
1927     DoSplashSetFileJarName(file_name, jar_name);
1928 
1929     /*
1930      * Done with all command line processing and potential re-execs so
1931      * clean up the environment.
1932      */
1933     (void)UnsetEnv(ENV_ENTRY);
1934     (void)UnsetEnv(SPLASH_FILE_ENV_ENTRY);
1935     (void)UnsetEnv(SPLASH_JAR_ENV_ENTRY);
1936 
1937     JLI_MemFree(splash_jar_entry);
1938     JLI_MemFree(splash_file_entry);
1939 
1940 }
1941 
1942 const char*
1943 GetDotVersion()
1944 {
1945     return _dVersion;
1946 }
1947 
1948 const char*
1949 GetFullVersion()
1950 {
1951     return _fVersion;
1952 }
1953 
1954 const char*
1955 GetProgramName()
1956 {
1957     return _program_name;
1958 }
1959 
1960 const char*
1961 GetLauncherName()
1962 {
1963     return _launcher_name;
1964 }
1965 
1966 jint
1967 GetErgoPolicy()
1968 {
1969     return _ergo_policy;
1970 }
1971 
1972 jboolean
1973 IsJavaArgs()
1974 {
1975     return _is_java_args;
1976 }
1977 
1978 static jboolean
1979 IsWildCardEnabled()
1980 {
1981     return _wc_enabled;
1982 }
1983 
1984 int
1985 ContinueInNewThread(InvocationFunctions* ifn, jlong threadStackSize,
1986                     int argc, char **argv,
1987                     int mode, char *what, int ret)
1988 {
1989 
1990     /*
1991      * If user doesn't specify stack size, check if VM has a preference.
1992      * Note that HotSpot no longer supports JNI_VERSION_1_1 but it will
1993      * return its default stack size through the init args structure.
1994      */
1995     if (threadStackSize == 0) {
1996       struct JDK1_1InitArgs args1_1;
1997       memset((void*)&args1_1, 0, sizeof(args1_1));
1998       args1_1.version = JNI_VERSION_1_1;
1999       ifn->GetDefaultJavaVMInitArgs(&args1_1);  /* ignore return value */
2000       if (args1_1.javaStackSize > 0) {
2001          threadStackSize = args1_1.javaStackSize;
2002       }
2003     }
2004 
2005     { /* Create a new thread to create JVM and invoke main method */
2006       JavaMainArgs args;
2007       int rslt;
2008 
2009       args.argc = argc;
2010       args.argv = argv;
2011       args.mode = mode;
2012       args.what = what;
2013       args.ifn = *ifn;
2014 
2015       rslt = ContinueInNewThread0(JavaMain, threadStackSize, (void*)&args);
2016       /* If the caller has deemed there is an error we
2017        * simply return that, otherwise we return the value of
2018        * the callee
2019        */
2020       return (ret != 0) ? ret : rslt;
2021     }
2022 }
2023 
2024 static void
2025 DumpState()
2026 {
2027     if (!JLI_IsTraceLauncher()) return ;
2028     printf("Launcher state:\n");
2029     printf("\tdebug:%s\n", (JLI_IsTraceLauncher() == JNI_TRUE) ? "on" : "off");
2030     printf("\tjavargs:%s\n", (_is_java_args == JNI_TRUE) ? "on" : "off");
2031     printf("\tprogram name:%s\n", GetProgramName());
2032     printf("\tlauncher name:%s\n", GetLauncherName());
2033     printf("\tjavaw:%s\n", (IsJavaw() == JNI_TRUE) ? "on" : "off");
2034     printf("\tfullversion:%s\n", GetFullVersion());
2035     printf("\tdotversion:%s\n", GetDotVersion());
2036     printf("\tergo_policy:");
2037     switch(GetErgoPolicy()) {
2038         case NEVER_SERVER_CLASS:
2039             printf("NEVER_ACT_AS_A_SERVER_CLASS_MACHINE\n");
2040             break;
2041         case ALWAYS_SERVER_CLASS:
2042             printf("ALWAYS_ACT_AS_A_SERVER_CLASS_MACHINE\n");
2043             break;
2044         default:
2045             printf("DEFAULT_ERGONOMICS_POLICY\n");
2046     }
2047 }
2048 
2049 /*
2050  * Return JNI_TRUE for an option string that has no effect but should
2051  * _not_ be passed on to the vm; return JNI_FALSE otherwise.  On
2052  * Solaris SPARC, this screening needs to be done if:
2053  *    -d32 or -d64 is passed to a binary with an unmatched data model
2054  *    (the exec in CreateExecutionEnvironment removes -d<n> options and points the
2055  *    exec to the proper binary).  In the case of when the data model and the
2056  *    requested version is matched, an exec would not occur, and these options
2057  *    were erroneously passed to the vm.
2058  */
2059 jboolean
2060 RemovableOption(char * option)
2061 {
2062   /*
2063    * Unconditionally remove both -d32 and -d64 options since only
2064    * the last such options has an effect; e.g.
2065    * java -d32 -d64 -d32 -version
2066    * is equivalent to
2067    * java -d32 -version
2068    */
2069 
2070   if( (JLI_StrCCmp(option, "-d32")  == 0 ) ||
2071       (JLI_StrCCmp(option, "-d64")  == 0 ) )
2072     return JNI_TRUE;
2073   else
2074     return JNI_FALSE;
2075 }
2076 
2077 /*
2078  * A utility procedure to always print to stderr
2079  */
2080 void
2081 JLI_ReportMessage(const char* fmt, ...)
2082 {
2083     va_list vl;
2084     va_start(vl, fmt);
2085     vfprintf(stderr, fmt, vl);
2086     fprintf(stderr, "\n");
2087     va_end(vl);
2088 }