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 static char     *listModules = NULL;
  73 
  74 static const char *_program_name;
  75 static const char *_launcher_name;
  76 static jboolean _is_java_args = JNI_FALSE;
  77 static jboolean _have_classpath = JNI_FALSE;
  78 static const char *_fVersion;
  79 static jboolean _wc_enabled = JNI_FALSE;
  80 static jint _ergo_policy = DEFAULT_POLICY;
  81 
  82 /*
  83  * Entries for splash screen environment variables.
  84  * putenv is performed in SelectVersion. We need
  85  * them in memory until UnsetEnv, so they are made static
  86  * global instead of auto local.
  87  */
  88 static char* splash_file_entry = NULL;
  89 static char* splash_jar_entry = NULL;
  90 
  91 /*
  92  * List of VM options to be specified when the VM is created.
  93  */
  94 static JavaVMOption *options;
  95 static int numOptions, maxOptions;
  96 
  97 /*
  98  * Prototypes for functions internal to launcher.
  99  */
 100 static void SetClassPath(const char *s);
 101 static void SetModulePath(const char *s);
 102 static void SetUpgradeModulePath(const char *s);
 103 static void SetMainModule(const char *s);
 104 static void SetAddModulesProp(const char *mods);
 105 static void SetLimitModulesProp(const char *mods);
 106 static void SetAddReadsProp(const jint n, const char *s);
 107 static void SetAddExportsProp(const jint n, const char *s);
 108 static void SetPatchProp(const jint n, const char *s);
 109 static void SelectVersion(int argc, char **argv, char **main_class);
 110 static void SetJvmEnvironment(int argc, char **argv);
 111 static jboolean ParseArguments(int *pargc, char ***pargv,
 112                                int *pmode, char **pwhat,
 113                                int *pret, const char *jrepath);
 114 static jboolean InitializeJVM(JavaVM **pvm, JNIEnv **penv,
 115                               InvocationFunctions *ifn);
 116 static jstring NewPlatformString(JNIEnv *env, char *s);
 117 static jclass LoadMainClass(JNIEnv *env, int mode, char *name);
 118 static jclass GetApplicationClass(JNIEnv *env);
 119 
 120 static void TranslateApplicationArgs(int jargc, const char **jargv, int *pargc, char ***pargv);
 121 static jboolean AddApplicationOptions(int cpathc, const char **cpathv);
 122 static void SetApplicationClassPath(const char**);
 123 
 124 static void PrintJavaVersion(JNIEnv *env, jboolean extraLF);
 125 static void PrintUsage(JNIEnv* env, jboolean doXUsage);
 126 static void ShowSettings(JNIEnv* env, char *optString);
 127 static void ListModules(JNIEnv* env, char *optString);

 128 
 129 static void SetPaths(int argc, char **argv);
 130 
 131 static void DumpState();
 132 static jboolean RemovableOption(char *option);
 133 
 134 /* Maximum supported entries from jvm.cfg. */
 135 #define INIT_MAX_KNOWN_VMS      10
 136 
 137 /* Values for vmdesc.flag */
 138 enum vmdesc_flag {
 139     VM_UNKNOWN = -1,
 140     VM_KNOWN,
 141     VM_ALIASED_TO,
 142     VM_WARN,
 143     VM_ERROR,
 144     VM_IF_SERVER_CLASS,
 145     VM_IGNORE
 146 };
 147 
 148 struct vmdesc {
 149     char *name;
 150     int flag;
 151     char *alias;
 152     char *server_class;
 153 };
 154 static struct vmdesc *knownVMs = NULL;
 155 static int knownVMsCount = 0;
 156 static int knownVMsLimit = 0;
 157 
 158 static void GrowKnownVMs(int minimum);
 159 static int  KnownVMIndex(const char* name);
 160 static void FreeKnownVMs();
 161 static jboolean IsWildCardEnabled();
 162 
 163 #define ARG_CHECK(AC_arg_count, AC_failure_message, AC_questionable_arg) \
 164     do { \
 165         if (AC_arg_count < 1) { \
 166             JLI_ReportErrorMessage(AC_failure_message, AC_questionable_arg); \
 167             printUsage = JNI_TRUE; \
 168             *pret = 1; \
 169             return JNI_TRUE; \
 170         } \
 171     } while (JNI_FALSE)
 172 
 173 /*
 174  * Running Java code in primordial thread caused many problems. We will
 175  * create a new thread to invoke JVM. See 6316197 for more information.
 176  */
 177 static jlong threadStackSize    = 0;  /* stack size of the new thread */
 178 static jlong maxHeapSize        = 0;  /* max heap size */
 179 static jlong initialHeapSize    = 0;  /* inital heap size */
 180 
 181 /*
 182  * A minimum -Xss stack size suitable for all platforms.
 183  */
 184 #ifndef STACK_SIZE_MINIMUM
 185 #define STACK_SIZE_MINIMUM (32 * KB)
 186 #endif
 187 
 188 /*
 189  * Entry point.
 190  */
 191 int
 192 JLI_Launch(int argc, char ** argv,              /* main argc, argc */
 193         int jargc, const char** jargv,          /* java args */
 194         int appclassc, const char** appclassv,  /* app classpath */
 195         const char* fullversion,                /* full version defined */
 196         const char* dotversion,                 /* UNUSED dot version defined */
 197         const char* pname,                      /* program name */
 198         const char* lname,                      /* launcher name */
 199         jboolean javaargs,                      /* JAVA_ARGS */
 200         jboolean cpwildcard,                    /* classpath wildcard*/
 201         jboolean javaw,                         /* windows-only javaw */
 202         jint ergo                               /* ergonomics class policy */
 203 )
 204 {
 205     int mode = LM_UNKNOWN;
 206     char *what = NULL;
 207     char *main_class = NULL;
 208     int ret;
 209     InvocationFunctions ifn;
 210     jlong start, end;
 211     char jvmpath[MAXPATHLEN];
 212     char jrepath[MAXPATHLEN];
 213     char jvmcfg[MAXPATHLEN];
 214 
 215     _fVersion = fullversion;
 216     _launcher_name = lname;
 217     _program_name = pname;
 218     _is_java_args = javaargs;
 219     _wc_enabled = cpwildcard;
 220     _ergo_policy = ergo;
 221 
 222     InitLauncher(javaw);
 223     DumpState();
 224     if (JLI_IsTraceLauncher()) {
 225         int i;
 226         printf("Command line args:\n");
 227         for (i = 0; i < argc ; i++) {
 228             printf("argv[%d] = %s\n", i, argv[i]);
 229         }
 230         AddOption("-Dsun.java.launcher.diag=true", NULL);
 231     }
 232 
 233     /*
 234      * SelectVersion() has several responsibilities:
 235      *
 236      *  1) Disallow specification of another JRE.  With 1.9, another
 237      *     version of the JRE cannot be invoked.
 238      *  2) Allow for a JRE version to invoke JDK 1.9 or later.  Since
 239      *     all mJRE directives have been stripped from the request but
 240      *     the pre 1.9 JRE [ 1.6 thru 1.8 ], it is as if 1.9+ has been
 241      *     invoked from the command line.
 242      */
 243     SelectVersion(argc, argv, &main_class);
 244 
 245     CreateExecutionEnvironment(&argc, &argv,
 246                                jrepath, sizeof(jrepath),
 247                                jvmpath, sizeof(jvmpath),
 248                                jvmcfg,  sizeof(jvmcfg));
 249 
 250     if (!IsJavaArgs()) {
 251         SetJvmEnvironment(argc,argv);
 252     }
 253 
 254     ifn.CreateJavaVM = 0;
 255     ifn.GetDefaultJavaVMInitArgs = 0;
 256 
 257     if (JLI_IsTraceLauncher()) {
 258         start = CounterGet();
 259     }
 260 
 261     if (!LoadJavaVM(jvmpath, &ifn)) {
 262         return(6);
 263     }
 264 
 265     if (JLI_IsTraceLauncher()) {
 266         end   = CounterGet();
 267     }
 268 
 269     JLI_TraceLauncher("%ld micro seconds to LoadJavaVM\n",
 270              (long)(jint)Counter2Micros(end-start));
 271 
 272     ++argv;
 273     --argc;
 274 
 275     if (IsJavaArgs()) {
 276         /* Preprocess wrapper arguments */
 277         TranslateApplicationArgs(jargc, jargv, &argc, &argv);
 278         if (!AddApplicationOptions(appclassc, appclassv)) {
 279             return(1);
 280         }
 281     } else {
 282         /* Set default CLASSPATH */
 283         char* cpath = getenv("CLASSPATH");
 284         if (cpath != NULL) {
 285             SetClassPath(cpath);
 286         }
 287     }
 288 
 289     /* Parse command line options; if the return value of
 290      * ParseArguments is false, the program should exit.
 291      */
 292     if (!ParseArguments(&argc, &argv, &mode, &what, &ret, jrepath))
 293     {
 294         return(ret);
 295     }
 296 
 297     /* Override class path if -jar flag was specified */
 298     if (mode == LM_JAR) {
 299         SetClassPath(what);     /* Override class path */
 300     }
 301 
 302     /* set the -Dsun.java.command pseudo property */
 303     SetJavaCommandLineProp(what, argc, argv);
 304 
 305     /* Set the -Dsun.java.launcher pseudo property */
 306     SetJavaLauncherProp();
 307 
 308     /* set the -Dsun.java.launcher.* platform properties */
 309     SetJavaLauncherPlatformProps();
 310 
 311     return JVMInit(&ifn, threadStackSize, argc, argv, mode, what, ret);
 312 }
 313 /*
 314  * Always detach the main thread so that it appears to have ended when
 315  * the application's main method exits.  This will invoke the
 316  * uncaught exception handler machinery if main threw an
 317  * exception.  An uncaught exception handler cannot change the
 318  * launcher's return code except by calling System.exit.
 319  *
 320  * Wait for all non-daemon threads to end, then destroy the VM.
 321  * This will actually create a trivial new Java waiter thread
 322  * named "DestroyJavaVM", but this will be seen as a different
 323  * thread from the one that executed main, even though they are
 324  * the same C thread.  This allows mainThread.join() and
 325  * mainThread.isAlive() to work as expected.
 326  */
 327 #define LEAVE() \

 328     do { \
 329         if ((*vm)->DetachCurrentThread(vm) != JNI_OK) { \
 330             JLI_ReportErrorMessage(JVM_ERROR2); \
 331             ret = 1; \
 332         } \
 333         if (JNI_TRUE) { \
 334             (*vm)->DestroyJavaVM(vm); \
 335             return ret; \
 336         } \
 337     } while (JNI_FALSE)
 338 
 339 #define CHECK_EXCEPTION_NULL_LEAVE(CENL_exception) \
 340     do { \
 341         if ((*env)->ExceptionOccurred(env)) { \
 342             JLI_ReportExceptionDescription(env); \
 343             LEAVE(); \
 344         } \
 345         if ((CENL_exception) == NULL) { \
 346             JLI_ReportErrorMessage(JNI_ERROR); \
 347             LEAVE(); \
 348         } \
 349     } while (JNI_FALSE)
 350 
 351 #define CHECK_EXCEPTION_LEAVE(CEL_return_value) \
 352     do { \
 353         if ((*env)->ExceptionOccurred(env)) { \
 354             JLI_ReportExceptionDescription(env); \
 355             ret = (CEL_return_value); \
 356             LEAVE(); \
 357         } \
 358     } while (JNI_FALSE)
 359 
 360 
 361 int JNICALL
 362 JavaMain(void * _args)
 363 {
 364     JavaMainArgs *args = (JavaMainArgs *)_args;
 365     int argc = args->argc;
 366     char **argv = args->argv;
 367     int mode = args->mode;
 368     char *what = args->what;
 369     InvocationFunctions ifn = args->ifn;
 370 
 371     JavaVM *vm = 0;
 372     JNIEnv *env = 0;
 373     jclass mainClass = NULL;
 374     jclass appClass = NULL; // actual application class being launched
 375     jmethodID mainID;
 376     jobjectArray mainArgs;
 377     int ret = 0;
 378     jlong start, end;
 379 
 380     RegisterThread();
 381 
 382     /* Initialize the virtual machine */
 383     start = CounterGet();
 384     if (!InitializeJVM(&vm, &env, &ifn)) {
 385         JLI_ReportErrorMessage(JVM_ERROR1);
 386         exit(1);
 387     }
 388 


 389     if (showSettings != NULL) {
 390         ShowSettings(env, showSettings);
 391         CHECK_EXCEPTION_LEAVE(1);
 392     }
 393 
 394     if (listModules != NULL) {
 395         ListModules(env, listModules);
 396         CHECK_EXCEPTION_LEAVE(1);
 397         LEAVE();
 398     }
 399 
 400     if (printVersion || showVersion) {
 401         PrintJavaVersion(env, showVersion);
 402         CHECK_EXCEPTION_LEAVE(0);
 403         if (printVersion) {
 404             LEAVE();
 405         }
 406     }
 407 
 408     /* If the user specified neither a class name nor a JAR file */
 409     if (printXUsage || printUsage || what == 0 || mode == LM_UNKNOWN) {
 410         PrintUsage(env, printXUsage);
 411         CHECK_EXCEPTION_LEAVE(1);
 412         LEAVE();
 413     }
 414 
 415     FreeKnownVMs();  /* after last possible PrintUsage() */
 416 
 417     if (JLI_IsTraceLauncher()) {
 418         end = CounterGet();
 419         JLI_TraceLauncher("%ld micro seconds to InitializeJVM\n",
 420                (long)(jint)Counter2Micros(end-start));
 421     }
 422 
 423     /* At this stage, argc/argv have the application's arguments */
 424     if (JLI_IsTraceLauncher()){
 425         int i;
 426         printf("%s is '%s'\n", launchModeNames[mode], what);
 427         printf("App's argc is %d\n", argc);
 428         for (i=0; i < argc; i++) {
 429             printf("    argv[%2d] = '%s'\n", i, argv[i]);
 430         }
 431     }
 432 
 433     ret = 1;
 434 
 435     /*
 436      * Get the application's main class.
 437      *
 438      * See bugid 5030265.  The Main-Class name has already been parsed
 439      * from the manifest, but not parsed properly for UTF-8 support.
 440      * Hence the code here ignores the value previously extracted and
 441      * uses the pre-existing code to reextract the value.  This is
 442      * possibly an end of release cycle expedient.  However, it has
 443      * also been discovered that passing some character sets through
 444      * the environment has "strange" behavior on some variants of
 445      * Windows.  Hence, maybe the manifest parsing code local to the
 446      * launcher should never be enhanced.
 447      *
 448      * Hence, future work should either:
 449      *     1)   Correct the local parsing code and verify that the
 450      *          Main-Class attribute gets properly passed through
 451      *          all environments,
 452      *     2)   Remove the vestages of maintaining main_class through
 453      *          the environment (and remove these comments).
 454      *
 455      * This method also correctly handles launching existing JavaFX
 456      * applications that may or may not have a Main-Class manifest entry.
 457      */
 458     mainClass = LoadMainClass(env, mode, what);
 459     CHECK_EXCEPTION_NULL_LEAVE(mainClass);
 460     /*
 461      * In some cases when launching an application that needs a helper, e.g., a
 462      * JavaFX application with no main method, the mainClass will not be the
 463      * applications own main class but rather a helper class. To keep things
 464      * consistent in the UI we need to track and report the application main class.
 465      */
 466     appClass = GetApplicationClass(env);
 467     NULL_CHECK_RETURN_VALUE(appClass, -1);
 468     /*
 469      * PostJVMInit uses the class name as the application name for GUI purposes,
 470      * for example, on OSX this sets the application name in the menu bar for
 471      * both SWT and JavaFX. So we'll pass the actual application class here
 472      * instead of mainClass as that may be a launcher or helper class instead
 473      * of the application class.
 474      */
 475     PostJVMInit(env, appClass, vm);
 476     CHECK_EXCEPTION_LEAVE(1);
 477     /*
 478      * The LoadMainClass not only loads the main class, it will also ensure
 479      * that the main method's signature is correct, therefore further checking
 480      * is not required. The main method is invoked here so that extraneous java
 481      * stacks are not in the application stack trace.
 482      */
 483     mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
 484                                        "([Ljava/lang/String;)V");
 485     CHECK_EXCEPTION_NULL_LEAVE(mainID);
 486 
 487     /* Build platform specific argument array */
 488     mainArgs = CreateApplicationArgs(env, argv, argc);
 489     CHECK_EXCEPTION_NULL_LEAVE(mainArgs);
 490 
 491     /* Invoke main method. */
 492     (*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);
 493 
 494     /*
 495      * The launcher's exit code (in the absence of calls to
 496      * System.exit) will be non-zero if main threw an exception.
 497      */
 498     ret = (*env)->ExceptionOccurred(env) == NULL ? 0 : 1;
 499     LEAVE();
 500 }
 501 
 502 /*
 503  * Checks the command line options to find which JVM type was
 504  * specified.  If no command line option was given for the JVM type,
 505  * the default type is used.  The environment variable
 506  * JDK_ALTERNATE_VM and the command line option -XXaltjvm= are also
 507  * checked as ways of specifying which JVM type to invoke.
 508  */
 509 char *
 510 CheckJvmType(int *pargc, char ***argv, jboolean speculative) {
 511     int i, argi;
 512     int argc;
 513     char **newArgv;
 514     int newArgvIdx = 0;
 515     int isVMType;
 516     int jvmidx = -1;
 517     char *jvmtype = getenv("JDK_ALTERNATE_VM");
 518 
 519     argc = *pargc;
 520 
 521     /* To make things simpler we always copy the argv array */
 522     newArgv = JLI_MemAlloc((argc + 1) * sizeof(char *));
 523 
 524     /* The program name is always present */
 525     newArgv[newArgvIdx++] = (*argv)[0];
 526 
 527     for (argi = 1; argi < argc; argi++) {
 528         char *arg = (*argv)[argi];
 529         isVMType = 0;
 530 
 531         if (IsJavaArgs()) {
 532             if (arg[0] != '-') {
 533                 newArgv[newArgvIdx++] = arg;
 534                 continue;
 535             }
 536         } else {
 537             if (JLI_StrCmp(arg, "-classpath") == 0 ||
 538                 JLI_StrCmp(arg, "-cp") == 0 ||
 539                 JLI_StrCmp(arg, "-modulepath") == 0 ||
 540                 JLI_StrCmp(arg, "-mp") == 0 ||
 541                 JLI_StrCmp(arg, "-upgrademodulepath") == 0 ||
 542                 JLI_StrCmp(arg, "-addmods") == 0 ||
 543                 JLI_StrCmp(arg, "-limitmods") == 0) {
 544                 newArgv[newArgvIdx++] = arg;
 545                 argi++;
 546                 if (argi < argc) {
 547                     newArgv[newArgvIdx++] = (*argv)[argi];
 548                 }
 549                 continue;
 550             }
 551             if (arg[0] != '-') break;
 552         }
 553 
 554         /* Did the user pass an explicit VM type? */
 555         i = KnownVMIndex(arg);
 556         if (i >= 0) {
 557             jvmtype = knownVMs[jvmidx = i].name + 1; /* skip the - */
 558             isVMType = 1;
 559             *pargc = *pargc - 1;
 560         }
 561 
 562         /* Did the user specify an "alternate" VM? */
 563         else if (JLI_StrCCmp(arg, "-XXaltjvm=") == 0 || JLI_StrCCmp(arg, "-J-XXaltjvm=") == 0) {
 564             isVMType = 1;
 565             jvmtype = arg+((arg[1]=='X')? 10 : 12);
 566             jvmidx = -1;
 567         }
 568 
 569         if (!isVMType) {
 570             newArgv[newArgvIdx++] = arg;
 571         }
 572     }
 573 
 574     /*
 575      * Finish copying the arguments if we aborted the above loop.
 576      * NOTE that if we aborted via "break" then we did NOT copy the
 577      * last argument above, and in addition argi will be less than
 578      * argc.
 579      */
 580     while (argi < argc) {
 581         newArgv[newArgvIdx++] = (*argv)[argi];
 582         argi++;
 583     }
 584 
 585     /* argv is null-terminated */
 586     newArgv[newArgvIdx] = 0;
 587 
 588     /* Copy back argv */
 589     *argv = newArgv;
 590     *pargc = newArgvIdx;
 591 
 592     /* use the default VM type if not specified (no alias processing) */
 593     if (jvmtype == NULL) {
 594       char* result = knownVMs[0].name+1;
 595       /* Use a different VM type if we are on a server class machine? */
 596       if ((knownVMs[0].flag == VM_IF_SERVER_CLASS) &&
 597           (ServerClassMachine() == JNI_TRUE)) {
 598         result = knownVMs[0].server_class+1;
 599       }
 600       JLI_TraceLauncher("Default VM: %s\n", result);
 601       return result;
 602     }
 603 
 604     /* if using an alternate VM, no alias processing */
 605     if (jvmidx < 0)
 606       return jvmtype;
 607 
 608     /* Resolve aliases first */
 609     {
 610       int loopCount = 0;
 611       while (knownVMs[jvmidx].flag == VM_ALIASED_TO) {
 612         int nextIdx = KnownVMIndex(knownVMs[jvmidx].alias);
 613 
 614         if (loopCount > knownVMsCount) {
 615           if (!speculative) {
 616             JLI_ReportErrorMessage(CFG_ERROR1);
 617             exit(1);
 618           } else {
 619             return "ERROR";
 620             /* break; */
 621           }
 622         }
 623 
 624         if (nextIdx < 0) {
 625           if (!speculative) {
 626             JLI_ReportErrorMessage(CFG_ERROR2, knownVMs[jvmidx].alias);
 627             exit(1);
 628           } else {
 629             return "ERROR";
 630           }
 631         }
 632         jvmidx = nextIdx;
 633         jvmtype = knownVMs[jvmidx].name+1;
 634         loopCount++;
 635       }
 636     }
 637 
 638     switch (knownVMs[jvmidx].flag) {
 639     case VM_WARN:
 640         if (!speculative) {
 641             JLI_ReportErrorMessage(CFG_WARN1, jvmtype, knownVMs[0].name + 1);
 642         }
 643         /* fall through */
 644     case VM_IGNORE:
 645         jvmtype = knownVMs[jvmidx=0].name + 1;
 646         /* fall through */
 647     case VM_KNOWN:
 648         break;
 649     case VM_ERROR:
 650         if (!speculative) {
 651             JLI_ReportErrorMessage(CFG_ERROR3, jvmtype);
 652             exit(1);
 653         } else {
 654             return "ERROR";
 655         }
 656     }
 657 
 658     return jvmtype;
 659 }
 660 
 661 /*
 662  * static void SetJvmEnvironment(int argc, char **argv);
 663  *   Is called just before the JVM is loaded.  We can set env variables
 664  *   that are consumed by the JVM.  This function is non-destructive,
 665  *   leaving the arg list intact.  The first use is for the JVM flag
 666  *   -XX:NativeMemoryTracking=value.
 667  */
 668 static void
 669 SetJvmEnvironment(int argc, char **argv) {
 670 
 671     static const char*  NMT_Env_Name    = "NMT_LEVEL_";
 672     int i;
 673     for (i = 0; i < argc; i++) {
 674         char *arg = argv[i];
 675         /*
 676          * Since this must be a VM flag we stop processing once we see
 677          * an argument the launcher would not have processed beyond (such
 678          * as -version or -h), or an argument that indicates the following
 679          * arguments are for the application (i.e. the main class name, or
 680          * the -jar argument).
 681          */
 682         if (i > 0) {
 683             char *prev = argv[i - 1];
 684             // skip non-dash arg preceded by class path specifiers
 685             if (*arg != '-' &&
 686                     ((JLI_StrCmp(prev, "-cp") == 0
 687                     || JLI_StrCmp(prev, "-classpath") == 0))) {
 688                 continue;
 689             }
 690 
 691             if (*arg != '-'
 692                     || JLI_StrCmp(arg, "-version") == 0
 693                     || JLI_StrCmp(arg, "-fullversion") == 0
 694                     || JLI_StrCmp(arg, "-help") == 0
 695                     || JLI_StrCmp(arg, "-?") == 0
 696                     || JLI_StrCmp(arg, "-jar") == 0
 697                     || JLI_StrCmp(arg, "-X") == 0) {
 698                 return;
 699             }
 700         }
 701         /*
 702          * The following case checks for "-XX:NativeMemoryTracking=value".
 703          * If value is non null, an environmental variable set to this value
 704          * will be created to be used by the JVM.
 705          * The argument is passed to the JVM, which will check validity.
 706          * The JVM is responsible for removing the env variable.
 707          */
 708         if (JLI_StrCCmp(arg, "-XX:NativeMemoryTracking=") == 0) {
 709             int retval;
 710             // get what follows this parameter, include "="
 711             size_t pnlen = JLI_StrLen("-XX:NativeMemoryTracking=");
 712             if (JLI_StrLen(arg) > pnlen) {
 713                 char* value = arg + pnlen;
 714                 size_t pbuflen = pnlen + JLI_StrLen(value) + 10; // 10 max pid digits
 715 
 716                 /*
 717                  * ensures that malloc successful
 718                  * DONT JLI_MemFree() pbuf.  JLI_PutEnv() uses system call
 719                  *   that could store the address.
 720                  */
 721                 char * pbuf = (char*)JLI_MemAlloc(pbuflen);
 722 
 723                 JLI_Snprintf(pbuf, pbuflen, "%s%d=%s", NMT_Env_Name, JLI_GetPid(), value);
 724                 retval = JLI_PutEnv(pbuf);
 725                 if (JLI_IsTraceLauncher()) {
 726                     char* envName;
 727                     char* envBuf;
 728 
 729                     // ensures that malloc successful
 730                     envName = (char*)JLI_MemAlloc(pbuflen);
 731                     JLI_Snprintf(envName, pbuflen, "%s%d", NMT_Env_Name, JLI_GetPid());
 732 
 733                     printf("TRACER_MARKER: NativeMemoryTracking: env var is %s\n",envName);
 734                     printf("TRACER_MARKER: NativeMemoryTracking: putenv arg %s\n",pbuf);
 735                     envBuf = getenv(envName);
 736                     printf("TRACER_MARKER: NativeMemoryTracking: got value %s\n",envBuf);
 737                     free(envName);
 738                 }
 739 
 740             }
 741 
 742         }
 743 
 744     }
 745 }
 746 
 747 /* copied from HotSpot function "atomll()" */
 748 static int
 749 parse_size(const char *s, jlong *result) {
 750   jlong n = 0;
 751   int args_read = sscanf(s, JLONG_FORMAT_SPECIFIER, &n);
 752   if (args_read != 1) {
 753     return 0;
 754   }
 755   while (*s != '\0' && *s >= '0' && *s <= '9') {
 756     s++;
 757   }
 758   // 4705540: illegal if more characters are found after the first non-digit
 759   if (JLI_StrLen(s) > 1) {
 760     return 0;
 761   }
 762   switch (*s) {
 763     case 'T': case 't':
 764       *result = n * GB * KB;
 765       return 1;
 766     case 'G': case 'g':
 767       *result = n * GB;
 768       return 1;
 769     case 'M': case 'm':
 770       *result = n * MB;
 771       return 1;
 772     case 'K': case 'k':
 773       *result = n * KB;
 774       return 1;
 775     case '\0':
 776       *result = n;
 777       return 1;
 778     default:
 779       /* Create JVM with default stack and let VM handle malformed -Xss string*/
 780       return 0;
 781   }
 782 }
 783 
 784 /*
 785  * Adds a new VM option with the given name and value.
 786  */
 787 void
 788 AddOption(char *str, void *info)
 789 {
 790     /*
 791      * Expand options array if needed to accommodate at least one more
 792      * VM option.
 793      */
 794     if (numOptions >= maxOptions) {
 795         if (options == 0) {
 796             maxOptions = 4;
 797             options = JLI_MemAlloc(maxOptions * sizeof(JavaVMOption));
 798         } else {
 799             JavaVMOption *tmp;
 800             maxOptions *= 2;
 801             tmp = JLI_MemAlloc(maxOptions * sizeof(JavaVMOption));
 802             memcpy(tmp, options, numOptions * sizeof(JavaVMOption));
 803             JLI_MemFree(options);
 804             options = tmp;
 805         }
 806     }
 807     options[numOptions].optionString = str;
 808     options[numOptions++].extraInfo = info;
 809 
 810     if (JLI_StrCCmp(str, "-Xss") == 0) {
 811         jlong tmp;
 812         if (parse_size(str + 4, &tmp)) {
 813             threadStackSize = tmp;
 814             /*
 815              * Make sure the thread stack size is big enough that we won't get a stack
 816              * overflow before the JVM startup code can check to make sure the stack
 817              * is big enough.
 818              */
 819             if (threadStackSize < (jlong)STACK_SIZE_MINIMUM) {
 820                 threadStackSize = STACK_SIZE_MINIMUM;
 821             }
 822         }
 823     }
 824 
 825     if (JLI_StrCCmp(str, "-Xmx") == 0) {
 826         jlong tmp;
 827         if (parse_size(str + 4, &tmp)) {
 828             maxHeapSize = tmp;
 829         }
 830     }
 831 
 832     if (JLI_StrCCmp(str, "-Xms") == 0) {
 833         jlong tmp;
 834         if (parse_size(str + 4, &tmp)) {
 835            initialHeapSize = tmp;
 836         }
 837     }
 838 }
 839 
 840 static void
 841 SetClassPath(const char *s)
 842 {
 843     char *def;
 844     const char *orig = s;
 845     static const char format[] = "-Djava.class.path=%s";
 846     /*
 847      * usually we should not get a null pointer, but there are cases where
 848      * we might just get one, in which case we simply ignore it, and let the
 849      * caller deal with it
 850      */
 851     if (s == NULL)
 852         return;
 853     s = JLI_WildcardExpandClasspath(s);
 854     if (sizeof(format) - 2 + JLI_StrLen(s) < JLI_StrLen(s))
 855         // s is became corrupted after expanding wildcards
 856         return;
 857     def = JLI_MemAlloc(sizeof(format)
 858                        - 2 /* strlen("%s") */
 859                        + JLI_StrLen(s));
 860     sprintf(def, format, s);
 861     AddOption(def, NULL);
 862     if (s != orig)
 863         JLI_MemFree((char *) s);
 864     _have_classpath = JNI_TRUE;
 865 }
 866 
 867 static void
 868 SetModulePath(const char *s)
 869 {
 870     char *def;
 871     const char *orig = s;
 872     static const char format[] = "-Djdk.module.path=%s";
 873     if (s == NULL)
 874         return;
 875     s = JLI_WildcardExpandClasspath(s);
 876     def = JLI_MemAlloc(sizeof(format)
 877                        - 2 /* strlen("%s") */
 878                        + JLI_StrLen(s));
 879     sprintf(def, format, s);
 880     AddOption(def, NULL);
 881     if (s != orig)
 882         JLI_MemFree((char *) s);
 883 }
 884 
 885 static void
 886 SetUpgradeModulePath(const char *s)
 887 {
 888     char *def;
 889     const char *orig = s;
 890     static const char format[] = "-Djdk.upgrade.module.path=%s";
 891     if (s == NULL)
 892         return;
 893     s = JLI_WildcardExpandClasspath(s);
 894     def = JLI_MemAlloc(sizeof(format)
 895                        - 2 /* strlen("%s") */
 896                        + JLI_StrLen(s));
 897     sprintf(def, format, s);
 898     AddOption(def, NULL);
 899     if (s != orig)
 900         JLI_MemFree((char *) s);
 901 }
 902 
 903 static void
 904 SetMainModule(const char *s)
 905 {
 906     static const char format[] = "-Djdk.module.main=%s";
 907     char* slash = JLI_StrChr(s, '/');
 908     size_t s_len, def_len;
 909     char *def;
 910 
 911     /* value may be <module> or <module>/<mainclass> */
 912     if (slash == NULL) {
 913         s_len = JLI_StrLen(s);
 914     } else {
 915         s_len = (size_t) (slash - s);
 916     }
 917     def_len = sizeof(format)
 918                - 2 /* strlen("%s") */
 919                + s_len;
 920     def = JLI_MemAlloc(def_len);
 921     JLI_Snprintf(def, def_len, format, s);
 922     AddOption(def, NULL);
 923 }
 924 
 925 static void
 926 SetAddModulesProp(const char *mods) {
 927     size_t buflen = JLI_StrLen(mods) + 40;
 928     char *prop = (char *)JLI_MemAlloc(buflen);
 929     JLI_Snprintf(prop, buflen, "-Djdk.launcher.addmods=%s", mods);
 930     AddOption(prop, NULL);
 931 }
 932 
 933 static void
 934 SetLimitModulesProp(const char *mods) {
 935     size_t buflen = JLI_StrLen(mods) + 40;
 936     char *prop = (char *)JLI_MemAlloc(buflen);
 937     JLI_Snprintf(prop, buflen, "-Djdk.launcher.limitmods=%s", mods);
 938     AddOption(prop, NULL);
 939 }
 940 
 941 static void
 942 SetAddReadsProp(const jint n, const char *s) {
 943     size_t buflen = JLI_StrLen(s) + 40;
 944     char *prop = (char *)JLI_MemAlloc(buflen);
 945     JLI_Snprintf(prop, buflen, "-Djdk.launcher.addreads.%d=%s", n, s);
 946     AddOption(prop, NULL);
 947 }
 948 
 949 static void
 950 SetAddExportsProp(const jint n, const char *s) {
 951     size_t buflen = JLI_StrLen(s) + 40;
 952     char *prop = (char *)JLI_MemAlloc(buflen);
 953     JLI_Snprintf(prop, buflen, "-Djdk.launcher.addexports.%d=%s", n, s);
 954     AddOption(prop, NULL);
 955 }
 956 
 957 static void
 958 SetPatchProp(const jint n, const char *s) {
 959     size_t buflen = JLI_StrLen(s) + 40;
 960     char *prop = (char *)JLI_MemAlloc(buflen);
 961     JLI_Snprintf(prop, buflen, "-Djdk.launcher.patch.%d=%s", n, s);
 962     AddOption(prop, NULL);
 963 }
 964 
 965 /*
 966  * The SelectVersion() routine ensures that an appropriate version of
 967  * the JRE is running.  The specification for the appropriate version
 968  * is obtained from either the manifest of a jar file (preferred) or
 969  * from command line options.
 970  * The routine also parses splash screen command line options and
 971  * passes on their values in private environment variables.
 972  */
 973 static void
 974 SelectVersion(int argc, char **argv, char **main_class)
 975 {
 976     char    *arg;
 977     char    *operand;
 978     char    *version = NULL;
 979     char    *jre = NULL;
 980     int     jarflag = 0;
 981     int     headlessflag = 0;
 982     int     restrict_search = -1;               /* -1 implies not known */
 983     manifest_info info;
 984     char    env_entry[MAXNAMELEN + 24] = ENV_ENTRY "=";
 985     char    *splash_file_name = NULL;
 986     char    *splash_jar_name = NULL;
 987     char    *env_in;
 988     int     res;
 989 
 990     /*
 991      * If the version has already been selected, set *main_class
 992      * with the value passed through the environment (if any) and
 993      * simply return.
 994      */
 995 
 996     /*
 997      * This environmental variable can be set by mJRE capable JREs
 998      * [ 1.5 thru 1.8 ].  All other aspects of mJRE processing have been
 999      * stripped by those JREs.  This environmental variable allows 1.9+
1000      * JREs to be started by these mJRE capable JREs.
1001      * Note that mJRE directives in the jar manifest file would have been
1002      * ignored for a JRE started by another JRE...
1003      * .. skipped for JRE 1.5 and beyond.
1004      * .. not even checked for pre 1.5.
1005      */
1006     if ((env_in = getenv(ENV_ENTRY)) != NULL) {
1007         if (*env_in != '\0')
1008             *main_class = JLI_StringDup(env_in);
1009         return;
1010     }
1011 
1012     /*
1013      * Scan through the arguments for options relevant to multiple JRE
1014      * support.  Multiple JRE support existed in JRE versions 1.5 thru 1.8.
1015      *
1016      * This capability is no longer available with JRE versions 1.9 and later.
1017      * These command line options are reported as errors.
1018      */
1019     argc--;
1020     argv++;
1021     while ((arg = *argv) != 0 && *arg == '-') {
1022         if (JLI_StrCCmp(arg, "-version:") == 0) {
1023             JLI_ReportErrorMessage(SPC_ERROR1);
1024         } else if (JLI_StrCmp(arg, "-jre-restrict-search") == 0) {
1025             JLI_ReportErrorMessage(SPC_ERROR2);
1026         } else if (JLI_StrCmp(arg, "-jre-no-restrict-search") == 0) {
1027             JLI_ReportErrorMessage(SPC_ERROR2);
1028         } else {
1029             if (JLI_StrCmp(arg, "-jar") == 0)
1030                 jarflag = 1;
1031             /* deal with "unfortunate" classpath syntax */
1032             if ((JLI_StrCmp(arg, "-classpath") == 0 || JLI_StrCmp(arg, "-cp") == 0) &&
1033               (argc >= 2)) {
1034                 argc--;
1035                 argv++;
1036                 arg = *argv;
1037             }
1038 
1039             /*
1040              * Checking for headless toolkit option in the some way as AWT does:
1041              * "true" means true and any other value means false
1042              */
1043             if (JLI_StrCmp(arg, "-Djava.awt.headless=true") == 0) {
1044                 headlessflag = 1;
1045             } else if (JLI_StrCCmp(arg, "-Djava.awt.headless=") == 0) {
1046                 headlessflag = 0;
1047             } else if (JLI_StrCCmp(arg, "-splash:") == 0) {
1048                 splash_file_name = arg+8;
1049             }
1050         }
1051         argc--;
1052         argv++;
1053     }
1054     if (argc <= 0) {    /* No operand? Possibly legit with -[full]version */
1055         operand = NULL;
1056     } else {
1057         argc--;
1058         operand = *argv++;
1059     }
1060 
1061     /*
1062      * If there is a jar file, read the manifest. If the jarfile can't be
1063      * read, the manifest can't be read from the jar file, or the manifest
1064      * is corrupt, issue the appropriate error messages and exit.
1065      *
1066      * Even if there isn't a jar file, construct a manifest_info structure
1067      * containing the command line information.  It's a convenient way to carry
1068      * this data around.
1069      */
1070     if (jarflag && operand) {
1071         if ((res = JLI_ParseManifest(operand, &info)) != 0) {
1072             if (res == -1)
1073                 JLI_ReportErrorMessage(JAR_ERROR2, operand);
1074             else
1075                 JLI_ReportErrorMessage(JAR_ERROR3, operand);
1076             exit(1);
1077         }
1078 
1079         /*
1080          * Command line splash screen option should have precedence
1081          * over the manifest, so the manifest data is used only if
1082          * splash_file_name has not been initialized above during command
1083          * line parsing
1084          */
1085         if (!headlessflag && !splash_file_name && info.splashscreen_image_file_name) {
1086             splash_file_name = info.splashscreen_image_file_name;
1087             splash_jar_name = operand;
1088         }
1089     } else {
1090         info.manifest_version = NULL;
1091         info.main_class = NULL;
1092         info.jre_version = NULL;
1093         info.jre_restrict_search = 0;
1094     }
1095 
1096     /*
1097      * Passing on splash screen info in environment variables
1098      */
1099     if (splash_file_name && !headlessflag) {
1100         char* splash_file_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_FILE_ENV_ENTRY "=")+JLI_StrLen(splash_file_name)+1);
1101         JLI_StrCpy(splash_file_entry, SPLASH_FILE_ENV_ENTRY "=");
1102         JLI_StrCat(splash_file_entry, splash_file_name);
1103         putenv(splash_file_entry);
1104     }
1105     if (splash_jar_name && !headlessflag) {
1106         char* splash_jar_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_JAR_ENV_ENTRY "=")+JLI_StrLen(splash_jar_name)+1);
1107         JLI_StrCpy(splash_jar_entry, SPLASH_JAR_ENV_ENTRY "=");
1108         JLI_StrCat(splash_jar_entry, splash_jar_name);
1109         putenv(splash_jar_entry);
1110     }
1111 
1112 
1113     /*
1114      * "Valid" returns (other than unrecoverable errors) follow.  Set
1115      * main_class as a side-effect of this routine.
1116      */
1117     if (info.main_class != NULL)
1118         *main_class = JLI_StringDup(info.main_class);
1119 
1120     if (info.jre_version == NULL) {
1121         JLI_FreeManifest();
1122         return;
1123     }
1124 
1125 }
1126 
1127 /*
1128  * Parses command line arguments.  Returns JNI_FALSE if launcher
1129  * should exit without starting vm, returns JNI_TRUE if vm needs
1130  * to be started to process given options.  *pret (the launcher
1131  * process return value) is set to 0 for a normal exit.
1132  */
1133 static jboolean
1134 ParseArguments(int *pargc, char ***pargv,
1135                int *pmode, char **pwhat,
1136                int *pret, const char *jrepath)
1137 {
1138     int argc = *pargc;
1139     char **argv = *pargv;
1140     int mode = LM_UNKNOWN;
1141     char *arg;
1142 
1143     *pret = 0;
1144 
1145     while ((arg = *argv) != 0 && *arg == '-') {
1146         argv++; --argc;
1147         if (JLI_StrCmp(arg, "-classpath") == 0 || JLI_StrCmp(arg, "-cp") == 0) {
1148             ARG_CHECK (argc, ARG_ERROR1, arg);
1149             SetClassPath(*argv);
1150             mode = LM_CLASS;
1151             argv++; --argc;
1152         } else if (JLI_StrCmp(arg, "-modulepath") == 0 || JLI_StrCmp(arg, "-mp") == 0) {
1153             ARG_CHECK (argc, ARG_ERROR4, arg);
1154             SetModulePath(*argv);
1155             argv++; --argc;
1156         } else if (JLI_StrCmp(arg, "-upgrademodulepath") == 0) {
1157             ARG_CHECK (argc, ARG_ERROR4, arg);
1158             SetUpgradeModulePath(*argv);
1159             argv++; --argc;
1160         } else if (JLI_StrCmp(arg, "-jar") == 0) {
1161             ARG_CHECK (argc, ARG_ERROR2, arg);
1162             mode = LM_JAR;
1163         } else if (JLI_StrCmp(arg, "-m") == 0) {
1164             ARG_CHECK (argc, ARG_ERROR5, arg);
1165             SetMainModule(*argv);
1166             mode = LM_MODULE;
1167         } else if (JLI_StrCmp(arg, "-addmods") == 0) {
1168             ARG_CHECK (argc, ARG_ERROR6, arg);
1169             SetAddModulesProp(*argv);
1170             argv++; --argc;
1171         } else if (JLI_StrCmp(arg, "-limitmods") == 0) {
1172             ARG_CHECK (argc, ARG_ERROR6, arg);
1173             SetLimitModulesProp(*argv);
1174             argv++; --argc;
1175         } else if (JLI_StrCmp(arg, "-listmods") == 0 ||
1176                    JLI_StrCCmp(arg, "-listmods:") == 0) {
1177             listModules = arg;
1178             return JNI_TRUE;
1179         } else if (JLI_StrCCmp(arg, "-XaddReads:") == 0) {
1180             static jint n;
1181             char *value = arg + 11;
1182             SetAddReadsProp(n++, value);
1183         } else if (JLI_StrCCmp(arg, "-XaddExports:") == 0) {
1184             static jint n;
1185             char *value = arg + 13;
1186             SetAddExportsProp(n++, value);
1187         } else if (JLI_StrCCmp(arg, "-Xpatch:") == 0) {
1188             static jint n;
1189             char *value = arg + 8;
1190             SetPatchProp(n++, value);
1191         } else if (JLI_StrCmp(arg, "-help") == 0 ||
1192                    JLI_StrCmp(arg, "-h") == 0 ||
1193                    JLI_StrCmp(arg, "-?") == 0) {
1194             printUsage = JNI_TRUE;
1195             return JNI_TRUE;
1196         } else if (JLI_StrCmp(arg, "-version") == 0) {
1197             printVersion = JNI_TRUE;
1198             return JNI_TRUE;
1199         } else if (JLI_StrCmp(arg, "-showversion") == 0) {
1200             showVersion = JNI_TRUE;
1201         } else if (JLI_StrCmp(arg, "-X") == 0) {
1202             printXUsage = JNI_TRUE;
1203             return JNI_TRUE;
1204 /*
1205  * The following case checks for -XshowSettings OR -XshowSetting:SUBOPT.
1206  * In the latter case, any SUBOPT value not recognized will default to "all"
1207  */
1208         } else if (JLI_StrCmp(arg, "-XshowSettings") == 0 ||
1209                    JLI_StrCCmp(arg, "-XshowSettings:") == 0) {
1210             showSettings = arg;
1211         } else if (JLI_StrCmp(arg, "-Xdiag") == 0) {
1212             AddOption("-Dsun.java.launcher.diag=true", NULL);
1213             AddOption("-Djdk.launcher.traceResolver=true", NULL);
1214         } else if (JLI_StrCmp(arg, "-Xdiag:resolver") == 0) {
1215             AddOption("-Djdk.launcher.traceResolver=true", NULL);
1216 /*
1217  * The following case provide backward compatibility with old-style
1218  * command line options.
1219  */
1220         } else if (JLI_StrCmp(arg, "-fullversion") == 0) {
1221             JLI_ReportMessage("%s full version \"%s\"", _launcher_name, GetFullVersion());
1222             return JNI_FALSE;
1223         } else if (JLI_StrCmp(arg, "-verbosegc") == 0) {
1224             AddOption("-verbose:gc", NULL);
1225         } else if (JLI_StrCmp(arg, "-t") == 0) {
1226             AddOption("-Xt", NULL);
1227         } else if (JLI_StrCmp(arg, "-tm") == 0) {
1228             AddOption("-Xtm", NULL);
1229         } else if (JLI_StrCmp(arg, "-debug") == 0) {
1230             AddOption("-Xdebug", NULL);
1231         } else if (JLI_StrCmp(arg, "-noclassgc") == 0) {
1232             AddOption("-Xnoclassgc", NULL);
1233         } else if (JLI_StrCmp(arg, "-Xfuture") == 0) {
1234             AddOption("-Xverify:all", NULL);
1235         } else if (JLI_StrCmp(arg, "-verify") == 0) {
1236             AddOption("-Xverify:all", NULL);
1237         } else if (JLI_StrCmp(arg, "-verifyremote") == 0) {
1238             AddOption("-Xverify:remote", NULL);
1239         } else if (JLI_StrCmp(arg, "-noverify") == 0) {
1240             AddOption("-Xverify:none", NULL);
1241         } else if (JLI_StrCCmp(arg, "-ss") == 0 ||
1242                    JLI_StrCCmp(arg, "-oss") == 0 ||
1243                    JLI_StrCCmp(arg, "-ms") == 0 ||
1244                    JLI_StrCCmp(arg, "-mx") == 0) {
1245             char *tmp = JLI_MemAlloc(JLI_StrLen(arg) + 6);
1246             sprintf(tmp, "-X%s", arg + 1); /* skip '-' */
1247             AddOption(tmp, NULL);
1248         } else if (JLI_StrCmp(arg, "-checksource") == 0 ||
1249                    JLI_StrCmp(arg, "-cs") == 0 ||
1250                    JLI_StrCmp(arg, "-noasyncgc") == 0) {
1251             /* No longer supported */
1252             JLI_ReportErrorMessage(ARG_WARN, arg);
1253         } else if (JLI_StrCCmp(arg, "-splash:") == 0) {
1254             ; /* Ignore machine independent options already handled */
1255         } else if (ProcessPlatformOption(arg)) {
1256             ; /* Processing of platform dependent options */
1257         } else if (RemovableOption(arg)) {
1258             ; /* Do not pass option to vm. */
1259         } else {
1260             /* java.class.path set on the command line */
1261             if (JLI_StrCCmp(arg, "-Djava.class.path=") == 0) {
1262                 _have_classpath = JNI_TRUE;
1263             }
1264             AddOption(arg, NULL);
1265         }
1266     }
1267 
1268     if (--argc >= 0) {
1269         *pwhat = *argv++;
1270     }
1271 
1272     if (*pwhat == NULL) {
1273         *pret = 1;
1274     } else if (mode == LM_UNKNOWN) {
1275         /* default to LM_CLASS if -m, -jar and -cp options are
1276          * not specified */
1277         if (!_have_classpath) {
1278             SetClassPath(".");
1279         }
1280         mode = LM_CLASS;
1281     }
1282 
1283     if (argc >= 0) {
1284         *pargc = argc;
1285         *pargv = argv;
1286     }
1287 
1288     *pmode = mode;
1289 
1290     return JNI_TRUE;
1291 }
1292 
1293 /*
1294  * Initializes the Java Virtual Machine. Also frees options array when
1295  * finished.
1296  */
1297 static jboolean
1298 InitializeJVM(JavaVM **pvm, JNIEnv **penv, InvocationFunctions *ifn)
1299 {
1300     JavaVMInitArgs args;
1301     jint r;
1302 
1303     memset(&args, 0, sizeof(args));
1304     args.version  = JNI_VERSION_1_2;
1305     args.nOptions = numOptions;
1306     args.options  = options;
1307     args.ignoreUnrecognized = JNI_FALSE;
1308 
1309     if (JLI_IsTraceLauncher()) {
1310         int i = 0;
1311         printf("JavaVM args:\n    ");
1312         printf("version 0x%08lx, ", (long)args.version);
1313         printf("ignoreUnrecognized is %s, ",
1314                args.ignoreUnrecognized ? "JNI_TRUE" : "JNI_FALSE");
1315         printf("nOptions is %ld\n", (long)args.nOptions);
1316         for (i = 0; i < numOptions; i++)
1317             printf("    option[%2d] = '%s'\n",
1318                    i, args.options[i].optionString);
1319     }
1320 
1321     r = ifn->CreateJavaVM(pvm, (void **)penv, &args);
1322     JLI_MemFree(options);
1323     return r == JNI_OK;
1324 }
1325 
1326 static jclass helperClass = NULL;
1327 
1328 jclass
1329 GetLauncherHelperClass(JNIEnv *env)
1330 {
1331     if (helperClass == NULL) {
1332         NULL_CHECK0(helperClass = FindBootStrapClass(env,
1333                 "sun/launcher/LauncherHelper"));
1334     }
1335     return helperClass;
1336 }
1337 
1338 static jmethodID makePlatformStringMID = NULL;
1339 /*
1340  * Returns a new Java string object for the specified platform string.
1341  */
1342 static jstring
1343 NewPlatformString(JNIEnv *env, char *s)
1344 {
1345     int len = (int)JLI_StrLen(s);
1346     jbyteArray ary;
1347     jclass cls = GetLauncherHelperClass(env);
1348     NULL_CHECK0(cls);
1349     if (s == NULL)
1350         return 0;
1351 
1352     ary = (*env)->NewByteArray(env, len);
1353     if (ary != 0) {
1354         jstring str = 0;
1355         (*env)->SetByteArrayRegion(env, ary, 0, len, (jbyte *)s);
1356         if (!(*env)->ExceptionOccurred(env)) {
1357             if (makePlatformStringMID == NULL) {
1358                 NULL_CHECK0(makePlatformStringMID = (*env)->GetStaticMethodID(env,
1359                         cls, "makePlatformString", "(Z[B)Ljava/lang/String;"));
1360             }
1361             str = (*env)->CallStaticObjectMethod(env, cls,
1362                     makePlatformStringMID, USE_STDERR, ary);
1363             (*env)->DeleteLocalRef(env, ary);
1364             return str;
1365         }
1366     }
1367     return 0;
1368 }
1369 
1370 /*
1371  * Returns a new array of Java string objects for the specified
1372  * array of platform strings.
1373  */
1374 jobjectArray
1375 NewPlatformStringArray(JNIEnv *env, char **strv, int strc)
1376 {
1377     jarray cls;
1378     jarray ary;
1379     int i;
1380 
1381     NULL_CHECK0(cls = FindBootStrapClass(env, "java/lang/String"));
1382     NULL_CHECK0(ary = (*env)->NewObjectArray(env, strc, cls, 0));
1383     for (i = 0; i < strc; i++) {
1384         jstring str = NewPlatformString(env, *strv++);
1385         NULL_CHECK0(str);
1386         (*env)->SetObjectArrayElement(env, ary, i, str);
1387         (*env)->DeleteLocalRef(env, str);
1388     }
1389     return ary;
1390 }
1391 
1392 /*
1393  * Loads a class and verifies that the main class is present and it is ok to
1394  * call it for more details refer to the java implementation.
1395  */
1396 static jclass
1397 LoadMainClass(JNIEnv *env, int mode, char *name)
1398 {
1399     jmethodID mid;
1400     jstring str;
1401     jobject result;
1402     jlong start, end;
1403     jclass cls = GetLauncherHelperClass(env);
1404     NULL_CHECK0(cls);
1405     if (JLI_IsTraceLauncher()) {
1406         start = CounterGet();
1407     }
1408     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1409                 "checkAndLoadMain",
1410                 "(ZILjava/lang/String;)Ljava/lang/Class;"));
1411 
1412     NULL_CHECK0(str = NewPlatformString(env, name));
1413     NULL_CHECK0(result = (*env)->CallStaticObjectMethod(env, cls, mid,
1414                                                         USE_STDERR, mode, str));
1415 
1416     if (JLI_IsTraceLauncher()) {
1417         end   = CounterGet();
1418         printf("%ld micro seconds to load main class\n",
1419                (long)(jint)Counter2Micros(end-start));
1420         printf("----%s----\n", JLDEBUG_ENV_ENTRY);
1421     }
1422 
1423     return (jclass)result;
1424 }
1425 
1426 static jclass
1427 GetApplicationClass(JNIEnv *env)
1428 {
1429     jmethodID mid;
1430     jclass cls = GetLauncherHelperClass(env);
1431     NULL_CHECK0(cls);
1432     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1433                 "getApplicationClass",
1434                 "()Ljava/lang/Class;"));
1435 
1436     return (*env)->CallStaticObjectMethod(env, cls, mid);
1437 }
1438 
1439 /*
1440  * For tools, convert command line args thus:
1441  *   javac -cp foo:foo/"*" -J-ms32m ...
1442  *   java -ms32m -cp JLI_WildcardExpandClasspath(foo:foo/"*") ...
1443  *
1444  * Takes 4 parameters, and returns the populated arguments
1445  */
1446 static void
1447 TranslateApplicationArgs(int jargc, const char **jargv, int *pargc, char ***pargv)
1448 {
1449     int argc = *pargc;
1450     char **argv = *pargv;
1451     int nargc = argc + jargc;
1452     char **nargv = JLI_MemAlloc((nargc + 1) * sizeof(char *));
1453     int i;
1454 
1455     *pargc = nargc;
1456     *pargv = nargv;
1457 
1458     /* Copy the VM arguments (i.e. prefixed with -J) */
1459     for (i = 0; i < jargc; i++) {
1460         const char *arg = jargv[i];
1461         if (arg[0] == '-' && arg[1] == 'J') {
1462             *nargv++ = ((arg + 2) == NULL) ? NULL : JLI_StringDup(arg + 2);
1463         }
1464     }
1465 
1466     for (i = 0; i < argc; i++) {
1467         char *arg = argv[i];
1468         if (arg[0] == '-' && arg[1] == 'J') {
1469             if (arg[2] == '\0') {
1470                 JLI_ReportErrorMessage(ARG_ERROR3);
1471                 exit(1);
1472             }
1473             *nargv++ = arg + 2;
1474         }
1475     }
1476 
1477     /* Copy the rest of the arguments */
1478     for (i = 0; i < jargc ; i++) {
1479         const char *arg = jargv[i];
1480         if (arg[0] != '-' || arg[1] != 'J') {
1481             *nargv++ = (arg == NULL) ? NULL : JLI_StringDup(arg);
1482         }
1483     }
1484     for (i = 0; i < argc; i++) {
1485         char *arg = argv[i];
1486         if (arg[0] == '-') {
1487             if (arg[1] == 'J')
1488                 continue;
1489             if (IsWildCardEnabled() && arg[1] == 'c'
1490                 && (JLI_StrCmp(arg, "-cp") == 0 ||
1491                     JLI_StrCmp(arg, "-classpath") == 0)
1492                 && i < argc - 1) {
1493                 *nargv++ = arg;
1494                 *nargv++ = (char *) JLI_WildcardExpandClasspath(argv[i+1]);
1495                 i++;
1496                 continue;
1497             }
1498         }
1499         *nargv++ = arg;
1500     }
1501     *nargv = 0;
1502 }
1503 
1504 /*
1505  * For our tools, we try to add 3 VM options:
1506  *      -Denv.class.path=<envcp>
1507  *      -Dapplication.home=<apphome>
1508  *      -Djava.class.path=<appcp>
1509  * <envcp>   is the user's setting of CLASSPATH -- for instance the user
1510  *           tells javac where to find binary classes through this environment
1511  *           variable.  Notice that users will be able to compile against our
1512  *           tools classes (sun.tools.javac.Main) only if they explicitly add
1513  *           tools.jar to CLASSPATH.
1514  * <apphome> is the directory where the application is installed.
1515  * <appcp>   is the classpath to where our apps' classfiles are.
1516  */
1517 static jboolean
1518 AddApplicationOptions(int cpathc, const char **cpathv)
1519 {
1520     char *envcp, *appcp, *apphome;
1521     char home[MAXPATHLEN]; /* application home */
1522     char separator[] = { PATH_SEPARATOR, '\0' };
1523     int size, i;
1524 
1525     {
1526         const char *s = getenv("CLASSPATH");
1527         if (s) {
1528             s = (char *) JLI_WildcardExpandClasspath(s);
1529             /* 40 for -Denv.class.path= */
1530             if (JLI_StrLen(s) + 40 > JLI_StrLen(s)) { // Safeguard from overflow
1531                 envcp = (char *)JLI_MemAlloc(JLI_StrLen(s) + 40);
1532                 sprintf(envcp, "-Denv.class.path=%s", s);
1533                 AddOption(envcp, NULL);
1534             }
1535         }
1536     }
1537 
1538     if (!GetApplicationHome(home, sizeof(home))) {
1539         JLI_ReportErrorMessage(CFG_ERROR5);
1540         return JNI_FALSE;
1541     }
1542 
1543     /* 40 for '-Dapplication.home=' */
1544     apphome = (char *)JLI_MemAlloc(JLI_StrLen(home) + 40);
1545     sprintf(apphome, "-Dapplication.home=%s", home);
1546     AddOption(apphome, NULL);
1547 
1548     /* How big is the application's classpath? */
1549     size = 40;                                 /* 40: "-Djava.class.path=" */
1550     for (i = 0; i < cpathc; i++) {
1551         size += (int)JLI_StrLen(home) + (int)JLI_StrLen(cpathv[i]) + 1; /* 1: separator */
1552     }
1553     appcp = (char *)JLI_MemAlloc(size + 1);
1554     JLI_StrCpy(appcp, "-Djava.class.path=");
1555     for (i = 0; i < cpathc; i++) {
1556         JLI_StrCat(appcp, home);                        /* c:\program files\myapp */
1557         JLI_StrCat(appcp, cpathv[i]);           /* \lib\myapp.jar         */
1558         JLI_StrCat(appcp, separator);           /* ;                      */
1559     }
1560     appcp[JLI_StrLen(appcp)-1] = '\0';  /* remove trailing path separator */
1561     AddOption(appcp, NULL);
1562     return JNI_TRUE;
1563 }
1564 
1565 /*
1566  * inject the -Dsun.java.command pseudo property into the args structure
1567  * this pseudo property is used in the HotSpot VM to expose the
1568  * Java class name and arguments to the main method to the VM. The
1569  * HotSpot VM uses this pseudo property to store the Java class name
1570  * (or jar file name) and the arguments to the class's main method
1571  * to the instrumentation memory region. The sun.java.command pseudo
1572  * property is not exported by HotSpot to the Java layer.
1573  */
1574 void
1575 SetJavaCommandLineProp(char *what, int argc, char **argv)
1576 {
1577 
1578     int i = 0;
1579     size_t len = 0;
1580     char* javaCommand = NULL;
1581     char* dashDstr = "-Dsun.java.command=";
1582 
1583     if (what == NULL) {
1584         /* unexpected, one of these should be set. just return without
1585          * setting the property
1586          */
1587         return;
1588     }
1589 
1590     /* determine the amount of memory to allocate assuming
1591      * the individual components will be space separated
1592      */
1593     len = JLI_StrLen(what);
1594     for (i = 0; i < argc; i++) {
1595         len += JLI_StrLen(argv[i]) + 1;
1596     }
1597 
1598     /* allocate the memory */
1599     javaCommand = (char*) JLI_MemAlloc(len + JLI_StrLen(dashDstr) + 1);
1600 
1601     /* build the -D string */
1602     *javaCommand = '\0';
1603     JLI_StrCat(javaCommand, dashDstr);
1604     JLI_StrCat(javaCommand, what);
1605 
1606     for (i = 0; i < argc; i++) {
1607         /* the components of the string are space separated. In
1608          * the case of embedded white space, the relationship of
1609          * the white space separated components to their true
1610          * positional arguments will be ambiguous. This issue may
1611          * be addressed in a future release.
1612          */
1613         JLI_StrCat(javaCommand, " ");
1614         JLI_StrCat(javaCommand, argv[i]);
1615     }
1616 
1617     AddOption(javaCommand, NULL);
1618 }
1619 
1620 /*
1621  * JVM would like to know if it's created by a standard Sun launcher, or by
1622  * user native application, the following property indicates the former.
1623  */
1624 void
1625 SetJavaLauncherProp() {
1626   AddOption("-Dsun.java.launcher=SUN_STANDARD", NULL);
1627 }
1628 
1629 /*
1630  * Prints the version information from the java.version and other properties.
1631  */
1632 static void
1633 PrintJavaVersion(JNIEnv *env, jboolean extraLF)
1634 {
1635     jclass ver;
1636     jmethodID print;
1637 
1638     NULL_CHECK(ver = FindBootStrapClass(env, "java/lang/VersionProps"));
1639     NULL_CHECK(print = (*env)->GetStaticMethodID(env,
1640                                                  ver,
1641                                                  (extraLF == JNI_TRUE) ? "println" : "print",
1642                                                  "()V"
1643                                                  )
1644               );
1645 
1646     (*env)->CallStaticVoidMethod(env, ver, print);
1647 }
1648 
1649 /*
1650  * Prints all the Java settings, see the java implementation for more details.
1651  */
1652 static void
1653 ShowSettings(JNIEnv *env, char *optString)
1654 {
1655     jmethodID showSettingsID;
1656     jstring joptString;
1657     jclass cls = GetLauncherHelperClass(env);
1658     NULL_CHECK(cls);
1659     NULL_CHECK(showSettingsID = (*env)->GetStaticMethodID(env, cls,
1660             "showSettings", "(ZLjava/lang/String;JJJZ)V"));
1661     NULL_CHECK(joptString = (*env)->NewStringUTF(env, optString));
1662     (*env)->CallStaticVoidMethod(env, cls, showSettingsID,
1663                                  USE_STDERR,
1664                                  joptString,
1665                                  (jlong)initialHeapSize,
1666                                  (jlong)maxHeapSize,
1667                                  (jlong)threadStackSize,
1668                                  ServerClassMachine());
1669 }
1670 
1671 /**
1672  * List modules supported by the runtime
1673  */
1674 static void
1675 ListModules(JNIEnv *env, char *optString)
1676 {
1677     jmethodID listModulesID;
1678     jstring joptString;
1679     jclass cls = GetLauncherHelperClass(env);
1680     NULL_CHECK(cls);
1681     NULL_CHECK(listModulesID = (*env)->GetStaticMethodID(env, cls,
1682             "listModules", "(ZLjava/lang/String;)V"));
1683     NULL_CHECK(joptString = (*env)->NewStringUTF(env, optString));
1684     (*env)->CallStaticVoidMethod(env, cls, listModulesID,
1685                                  USE_STDERR,
1686                                  joptString);































1687 }
1688 
1689 /*
1690  * Prints default usage or the Xusage message, see sun.launcher.LauncherHelper.java
1691  */
1692 static void
1693 PrintUsage(JNIEnv* env, jboolean doXUsage)
1694 {
1695   jmethodID initHelp, vmSelect, vmSynonym, vmErgo, printHelp, printXUsageMessage;
1696   jstring jprogname, vm1, vm2;
1697   int i;
1698   jclass cls = GetLauncherHelperClass(env);
1699   NULL_CHECK(cls);
1700   if (doXUsage) {
1701     NULL_CHECK(printXUsageMessage = (*env)->GetStaticMethodID(env, cls,
1702                                         "printXUsageMessage", "(Z)V"));
1703     (*env)->CallStaticVoidMethod(env, cls, printXUsageMessage, USE_STDERR);
1704   } else {
1705     NULL_CHECK(initHelp = (*env)->GetStaticMethodID(env, cls,
1706                                         "initHelpMessage", "(Ljava/lang/String;)V"));
1707 
1708     NULL_CHECK(vmSelect = (*env)->GetStaticMethodID(env, cls, "appendVmSelectMessage",
1709                                         "(Ljava/lang/String;Ljava/lang/String;)V"));
1710 
1711     NULL_CHECK(vmSynonym = (*env)->GetStaticMethodID(env, cls,
1712                                         "appendVmSynonymMessage",
1713                                         "(Ljava/lang/String;Ljava/lang/String;)V"));
1714     NULL_CHECK(vmErgo = (*env)->GetStaticMethodID(env, cls,
1715                                         "appendVmErgoMessage", "(ZLjava/lang/String;)V"));
1716 
1717     NULL_CHECK(printHelp = (*env)->GetStaticMethodID(env, cls,
1718                                         "printHelpMessage", "(Z)V"));
1719 
1720     NULL_CHECK(jprogname = (*env)->NewStringUTF(env, _program_name));
1721 
1722     /* Initialize the usage message with the usual preamble */
1723     (*env)->CallStaticVoidMethod(env, cls, initHelp, jprogname);
1724     CHECK_EXCEPTION_RETURN();
1725 
1726 
1727     /* Assemble the other variant part of the usage */
1728     if ((knownVMs[0].flag == VM_KNOWN) ||
1729         (knownVMs[0].flag == VM_IF_SERVER_CLASS)) {
1730       NULL_CHECK(vm1 = (*env)->NewStringUTF(env, knownVMs[0].name));
1731       NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[0].name+1));
1732       (*env)->CallStaticVoidMethod(env, cls, vmSelect, vm1, vm2);
1733       CHECK_EXCEPTION_RETURN();
1734     }
1735     for (i=1; i<knownVMsCount; i++) {
1736       if (knownVMs[i].flag == VM_KNOWN) {
1737         NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
1738         NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].name+1));
1739         (*env)->CallStaticVoidMethod(env, cls, vmSelect, vm1, vm2);
1740         CHECK_EXCEPTION_RETURN();
1741       }
1742     }
1743     for (i=1; i<knownVMsCount; i++) {
1744       if (knownVMs[i].flag == VM_ALIASED_TO) {
1745         NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
1746         NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].alias+1));
1747         (*env)->CallStaticVoidMethod(env, cls, vmSynonym, vm1, vm2);
1748         CHECK_EXCEPTION_RETURN();
1749       }
1750     }
1751 
1752     /* The first known VM is the default */
1753     {
1754       jboolean isServerClassMachine = ServerClassMachine();
1755 
1756       const char* defaultVM  =  knownVMs[0].name+1;
1757       if ((knownVMs[0].flag == VM_IF_SERVER_CLASS) && isServerClassMachine) {
1758         defaultVM = knownVMs[0].server_class+1;
1759       }
1760 
1761       NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, defaultVM));
1762       (*env)->CallStaticVoidMethod(env, cls, vmErgo, isServerClassMachine,  vm1);
1763       CHECK_EXCEPTION_RETURN();
1764     }
1765 
1766     /* Complete the usage message and print to stderr*/
1767     (*env)->CallStaticVoidMethod(env, cls, printHelp, USE_STDERR);
1768   }
1769   return;
1770 }
1771 
1772 /*
1773  * Read the jvm.cfg file and fill the knownJVMs[] array.
1774  *
1775  * The functionality of the jvm.cfg file is subject to change without
1776  * notice and the mechanism will be removed in the future.
1777  *
1778  * The lexical structure of the jvm.cfg file is as follows:
1779  *
1780  *     jvmcfg         :=  { vmLine }
1781  *     vmLine         :=  knownLine
1782  *                    |   aliasLine
1783  *                    |   warnLine
1784  *                    |   ignoreLine
1785  *                    |   errorLine
1786  *                    |   predicateLine
1787  *                    |   commentLine
1788  *     knownLine      :=  flag  "KNOWN"                  EOL
1789  *     warnLine       :=  flag  "WARN"                   EOL
1790  *     ignoreLine     :=  flag  "IGNORE"                 EOL
1791  *     errorLine      :=  flag  "ERROR"                  EOL
1792  *     aliasLine      :=  flag  "ALIASED_TO"       flag  EOL
1793  *     predicateLine  :=  flag  "IF_SERVER_CLASS"  flag  EOL
1794  *     commentLine    :=  "#" text                       EOL
1795  *     flag           :=  "-" identifier
1796  *
1797  * The semantics are that when someone specifies a flag on the command line:
1798  * - if the flag appears on a knownLine, then the identifier is used as
1799  *   the name of the directory holding the JVM library (the name of the JVM).
1800  * - if the flag appears as the first flag on an aliasLine, the identifier
1801  *   of the second flag is used as the name of the JVM.
1802  * - if the flag appears on a warnLine, the identifier is used as the
1803  *   name of the JVM, but a warning is generated.
1804  * - if the flag appears on an ignoreLine, the identifier is recognized as the
1805  *   name of a JVM, but the identifier is ignored and the default vm used
1806  * - if the flag appears on an errorLine, an error is generated.
1807  * - if the flag appears as the first flag on a predicateLine, and
1808  *   the machine on which you are running passes the predicate indicated,
1809  *   then the identifier of the second flag is used as the name of the JVM,
1810  *   otherwise the identifier of the first flag is used as the name of the JVM.
1811  * If no flag is given on the command line, the first vmLine of the jvm.cfg
1812  * file determines the name of the JVM.
1813  * PredicateLines are only interpreted on first vmLine of a jvm.cfg file,
1814  * since they only make sense if someone hasn't specified the name of the
1815  * JVM on the command line.
1816  *
1817  * The intent of the jvm.cfg file is to allow several JVM libraries to
1818  * be installed in different subdirectories of a single JRE installation,
1819  * for space-savings and convenience in testing.
1820  * The intent is explicitly not to provide a full aliasing or predicate
1821  * mechanism.
1822  */
1823 jint
1824 ReadKnownVMs(const char *jvmCfgName, jboolean speculative)
1825 {
1826     FILE *jvmCfg;
1827     char line[MAXPATHLEN+20];
1828     int cnt = 0;
1829     int lineno = 0;
1830     jlong start, end;
1831     int vmType;
1832     char *tmpPtr;
1833     char *altVMName = NULL;
1834     char *serverClassVMName = NULL;
1835     static char *whiteSpace = " \t";
1836     if (JLI_IsTraceLauncher()) {
1837         start = CounterGet();
1838     }
1839 
1840     jvmCfg = fopen(jvmCfgName, "r");
1841     if (jvmCfg == NULL) {
1842       if (!speculative) {
1843         JLI_ReportErrorMessage(CFG_ERROR6, jvmCfgName);
1844         exit(1);
1845       } else {
1846         return -1;
1847       }
1848     }
1849     while (fgets(line, sizeof(line), jvmCfg) != NULL) {
1850         vmType = VM_UNKNOWN;
1851         lineno++;
1852         if (line[0] == '#')
1853             continue;
1854         if (line[0] != '-') {
1855             JLI_ReportErrorMessage(CFG_WARN2, lineno, jvmCfgName);
1856         }
1857         if (cnt >= knownVMsLimit) {
1858             GrowKnownVMs(cnt);
1859         }
1860         line[JLI_StrLen(line)-1] = '\0'; /* remove trailing newline */
1861         tmpPtr = line + JLI_StrCSpn(line, whiteSpace);
1862         if (*tmpPtr == 0) {
1863             JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
1864         } else {
1865             /* Null-terminate this string for JLI_StringDup below */
1866             *tmpPtr++ = 0;
1867             tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
1868             if (*tmpPtr == 0) {
1869                 JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
1870             } else {
1871                 if (!JLI_StrCCmp(tmpPtr, "KNOWN")) {
1872                     vmType = VM_KNOWN;
1873                 } else if (!JLI_StrCCmp(tmpPtr, "ALIASED_TO")) {
1874                     tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
1875                     if (*tmpPtr != 0) {
1876                         tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
1877                     }
1878                     if (*tmpPtr == 0) {
1879                         JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
1880                     } else {
1881                         /* Null terminate altVMName */
1882                         altVMName = tmpPtr;
1883                         tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
1884                         *tmpPtr = 0;
1885                         vmType = VM_ALIASED_TO;
1886                     }
1887                 } else if (!JLI_StrCCmp(tmpPtr, "WARN")) {
1888                     vmType = VM_WARN;
1889                 } else if (!JLI_StrCCmp(tmpPtr, "IGNORE")) {
1890                     vmType = VM_IGNORE;
1891                 } else if (!JLI_StrCCmp(tmpPtr, "ERROR")) {
1892                     vmType = VM_ERROR;
1893                 } else if (!JLI_StrCCmp(tmpPtr, "IF_SERVER_CLASS")) {
1894                     tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
1895                     if (*tmpPtr != 0) {
1896                         tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
1897                     }
1898                     if (*tmpPtr == 0) {
1899                         JLI_ReportErrorMessage(CFG_WARN4, lineno, jvmCfgName);
1900                     } else {
1901                         /* Null terminate server class VM name */
1902                         serverClassVMName = tmpPtr;
1903                         tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
1904                         *tmpPtr = 0;
1905                         vmType = VM_IF_SERVER_CLASS;
1906                     }
1907                 } else {
1908                     JLI_ReportErrorMessage(CFG_WARN5, lineno, &jvmCfgName[0]);
1909                     vmType = VM_KNOWN;
1910                 }
1911             }
1912         }
1913 
1914         JLI_TraceLauncher("jvm.cfg[%d] = ->%s<-\n", cnt, line);
1915         if (vmType != VM_UNKNOWN) {
1916             knownVMs[cnt].name = JLI_StringDup(line);
1917             knownVMs[cnt].flag = vmType;
1918             switch (vmType) {
1919             default:
1920                 break;
1921             case VM_ALIASED_TO:
1922                 knownVMs[cnt].alias = JLI_StringDup(altVMName);
1923                 JLI_TraceLauncher("    name: %s  vmType: %s  alias: %s\n",
1924                    knownVMs[cnt].name, "VM_ALIASED_TO", knownVMs[cnt].alias);
1925                 break;
1926             case VM_IF_SERVER_CLASS:
1927                 knownVMs[cnt].server_class = JLI_StringDup(serverClassVMName);
1928                 JLI_TraceLauncher("    name: %s  vmType: %s  server_class: %s\n",
1929                     knownVMs[cnt].name, "VM_IF_SERVER_CLASS", knownVMs[cnt].server_class);
1930                 break;
1931             }
1932             cnt++;
1933         }
1934     }
1935     fclose(jvmCfg);
1936     knownVMsCount = cnt;
1937 
1938     if (JLI_IsTraceLauncher()) {
1939         end   = CounterGet();
1940         printf("%ld micro seconds to parse jvm.cfg\n",
1941                (long)(jint)Counter2Micros(end-start));
1942     }
1943 
1944     return cnt;
1945 }
1946 
1947 
1948 static void
1949 GrowKnownVMs(int minimum)
1950 {
1951     struct vmdesc* newKnownVMs;
1952     int newMax;
1953 
1954     newMax = (knownVMsLimit == 0 ? INIT_MAX_KNOWN_VMS : (2 * knownVMsLimit));
1955     if (newMax <= minimum) {
1956         newMax = minimum;
1957     }
1958     newKnownVMs = (struct vmdesc*) JLI_MemAlloc(newMax * sizeof(struct vmdesc));
1959     if (knownVMs != NULL) {
1960         memcpy(newKnownVMs, knownVMs, knownVMsLimit * sizeof(struct vmdesc));
1961     }
1962     JLI_MemFree(knownVMs);
1963     knownVMs = newKnownVMs;
1964     knownVMsLimit = newMax;
1965 }
1966 
1967 
1968 /* Returns index of VM or -1 if not found */
1969 static int
1970 KnownVMIndex(const char* name)
1971 {
1972     int i;
1973     if (JLI_StrCCmp(name, "-J") == 0) name += 2;
1974     for (i = 0; i < knownVMsCount; i++) {
1975         if (!JLI_StrCmp(name, knownVMs[i].name)) {
1976             return i;
1977         }
1978     }
1979     return -1;
1980 }
1981 
1982 static void
1983 FreeKnownVMs()
1984 {
1985     int i;
1986     for (i = 0; i < knownVMsCount; i++) {
1987         JLI_MemFree(knownVMs[i].name);
1988         knownVMs[i].name = NULL;
1989     }
1990     JLI_MemFree(knownVMs);
1991 }
1992 
1993 /*
1994  * Displays the splash screen according to the jar file name
1995  * and image file names stored in environment variables
1996  */
1997 void
1998 ShowSplashScreen()
1999 {
2000     const char *jar_name = getenv(SPLASH_JAR_ENV_ENTRY);
2001     const char *file_name = getenv(SPLASH_FILE_ENV_ENTRY);
2002     int data_size;
2003     void *image_data = NULL;
2004     float scale_factor = 1;
2005     char *scaled_splash_name = NULL;
2006     jboolean isImageScaled = JNI_FALSE;
2007     size_t maxScaledImgNameLength = 0;
2008     if (file_name == NULL){
2009         return;
2010     }
2011     maxScaledImgNameLength = DoSplashGetScaledImgNameMaxPstfixLen(file_name);
2012 
2013     scaled_splash_name = JLI_MemAlloc(
2014                             maxScaledImgNameLength * sizeof(char));
2015     isImageScaled = DoSplashGetScaledImageName(jar_name, file_name,
2016                             &scale_factor,
2017                             scaled_splash_name, maxScaledImgNameLength);
2018     if (jar_name) {
2019 
2020         if (isImageScaled) {
2021             image_data = JLI_JarUnpackFile(
2022                     jar_name, scaled_splash_name, &data_size);
2023         }
2024 
2025         if (!image_data) {
2026             scale_factor = 1;
2027             image_data = JLI_JarUnpackFile(
2028                             jar_name, file_name, &data_size);
2029         }
2030         if (image_data) {
2031             DoSplashInit();
2032             DoSplashSetScaleFactor(scale_factor);
2033             DoSplashLoadMemory(image_data, data_size);
2034             JLI_MemFree(image_data);
2035         }
2036     } else {
2037         DoSplashInit();
2038         if (isImageScaled) {
2039             DoSplashSetScaleFactor(scale_factor);
2040             DoSplashLoadFile(scaled_splash_name);
2041         } else {
2042             DoSplashLoadFile(file_name);
2043         }
2044     }
2045     JLI_MemFree(scaled_splash_name);
2046 
2047     DoSplashSetFileJarName(file_name, jar_name);
2048 
2049     /*
2050      * Done with all command line processing and potential re-execs so
2051      * clean up the environment.
2052      */
2053     (void)UnsetEnv(ENV_ENTRY);
2054     (void)UnsetEnv(SPLASH_FILE_ENV_ENTRY);
2055     (void)UnsetEnv(SPLASH_JAR_ENV_ENTRY);
2056 
2057     JLI_MemFree(splash_jar_entry);
2058     JLI_MemFree(splash_file_entry);
2059 
2060 }
2061 
2062 const char*
2063 GetFullVersion()
2064 {
2065     return _fVersion;
2066 }
2067 
2068 const char*
2069 GetProgramName()
2070 {
2071     return _program_name;
2072 }
2073 
2074 const char*
2075 GetLauncherName()
2076 {
2077     return _launcher_name;
2078 }
2079 
2080 jint
2081 GetErgoPolicy()
2082 {
2083     return _ergo_policy;
2084 }
2085 
2086 jboolean
2087 IsJavaArgs()
2088 {
2089     return _is_java_args;
2090 }
2091 
2092 static jboolean
2093 IsWildCardEnabled()
2094 {
2095     return _wc_enabled;
2096 }
2097 
2098 int
2099 ContinueInNewThread(InvocationFunctions* ifn, jlong threadStackSize,
2100                     int argc, char **argv,
2101                     int mode, char *what, int ret)
2102 {
2103 
2104     /*
2105      * If user doesn't specify stack size, check if VM has a preference.
2106      * Note that HotSpot no longer supports JNI_VERSION_1_1 but it will
2107      * return its default stack size through the init args structure.
2108      */
2109     if (threadStackSize == 0) {
2110       struct JDK1_1InitArgs args1_1;
2111       memset((void*)&args1_1, 0, sizeof(args1_1));
2112       args1_1.version = JNI_VERSION_1_1;
2113       ifn->GetDefaultJavaVMInitArgs(&args1_1);  /* ignore return value */
2114       if (args1_1.javaStackSize > 0) {
2115          threadStackSize = args1_1.javaStackSize;
2116       }
2117     }
2118 
2119     { /* Create a new thread to create JVM and invoke main method */
2120       JavaMainArgs args;
2121       int rslt;
2122 
2123       args.argc = argc;
2124       args.argv = argv;
2125       args.mode = mode;
2126       args.what = what;
2127       args.ifn = *ifn;
2128 
2129       rslt = ContinueInNewThread0(JavaMain, threadStackSize, (void*)&args);
2130       /* If the caller has deemed there is an error we
2131        * simply return that, otherwise we return the value of
2132        * the callee
2133        */
2134       return (ret != 0) ? ret : rslt;
2135     }
2136 }
2137 
2138 static void
2139 DumpState()
2140 {
2141     if (!JLI_IsTraceLauncher()) return ;
2142     printf("Launcher state:\n");
2143     printf("\tFirst application arg index: %d\n", JLI_GetAppArgIndex());
2144     printf("\tdebug:%s\n", (JLI_IsTraceLauncher() == JNI_TRUE) ? "on" : "off");
2145     printf("\tjavargs:%s\n", (_is_java_args == JNI_TRUE) ? "on" : "off");
2146     printf("\tprogram name:%s\n", GetProgramName());
2147     printf("\tlauncher name:%s\n", GetLauncherName());
2148     printf("\tjavaw:%s\n", (IsJavaw() == JNI_TRUE) ? "on" : "off");
2149     printf("\tfullversion:%s\n", GetFullVersion());
2150     printf("\tergo_policy:");
2151     switch(GetErgoPolicy()) {
2152         case NEVER_SERVER_CLASS:
2153             printf("NEVER_ACT_AS_A_SERVER_CLASS_MACHINE\n");
2154             break;
2155         case ALWAYS_SERVER_CLASS:
2156             printf("ALWAYS_ACT_AS_A_SERVER_CLASS_MACHINE\n");
2157             break;
2158         default:
2159             printf("DEFAULT_ERGONOMICS_POLICY\n");
2160     }
2161 }
2162 
2163 /*
2164  * Return JNI_TRUE for an option string that has no effect but should
2165  * _not_ be passed on to the vm; return JNI_FALSE otherwise.  On
2166  * Solaris SPARC, this screening needs to be done if:
2167  *    -d32 or -d64 is passed to a binary with an unmatched data model
2168  *    (the exec in CreateExecutionEnvironment removes -d<n> options and points the
2169  *    exec to the proper binary).  In the case of when the data model and the
2170  *    requested version is matched, an exec would not occur, and these options
2171  *    were erroneously passed to the vm.
2172  */
2173 jboolean
2174 RemovableOption(char * option)
2175 {
2176   /*
2177    * Unconditionally remove both -d32 and -d64 options since only
2178    * the last such options has an effect; e.g.
2179    * java -d32 -d64 -d32 -version
2180    * is equivalent to
2181    * java -d32 -version
2182    */
2183 
2184   if( (JLI_StrCCmp(option, "-d32")  == 0 ) ||
2185       (JLI_StrCCmp(option, "-d64")  == 0 ) )
2186     return JNI_TRUE;
2187   else
2188     return JNI_FALSE;
2189 }
2190 
2191 /*
2192  * A utility procedure to always print to stderr
2193  */
2194 void
2195 JLI_ReportMessage(const char* fmt, ...)
2196 {
2197     va_list vl;
2198     va_start(vl, fmt);
2199     vfprintf(stderr, fmt, vl);
2200     fprintf(stderr, "\n");
2201     va_end(vl);
2202 }
--- EOF ---