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