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