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