1 /*
   2  * Copyright (c) 1995, 2018, 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 #include "jni.h"
  56 
  57 /*
  58  * A NOTE TO DEVELOPERS: For performance reasons it is important that
  59  * the program image remain relatively small until after SelectVersion
  60  * CreateExecutionEnvironment have finished their possibly recursive
  61  * processing. Watch everything, but resist all temptations to use Java
  62  * interfaces.
  63  */
  64 
  65 #define USE_STDERR JNI_TRUE     /* we usually print to stderr */
  66 #define USE_STDOUT JNI_FALSE
  67 
  68 static jboolean printVersion = JNI_FALSE; /* print and exit */
  69 static jboolean showVersion = JNI_FALSE;  /* print but continue */
  70 static jboolean printUsage = JNI_FALSE;   /* print and exit*/
  71 static jboolean printTo = USE_STDERR;     /* where to print version/usage */
  72 static jboolean printXUsage = JNI_FALSE;  /* print and exit*/
  73 static jboolean dryRun = JNI_FALSE;       /* initialize VM and exit */
  74 static char     *showSettings = NULL;     /* print but continue */
  75 static jboolean showResolvedModules = JNI_FALSE;
  76 static jboolean listModules = JNI_FALSE;
  77 static char     *describeModule = NULL;
  78 static jboolean validateModules = JNI_FALSE;
  79 
  80 static const char *_program_name;
  81 static const char *_launcher_name;
  82 static jboolean _is_java_args = JNI_FALSE;
  83 static jboolean _have_classpath = JNI_FALSE;
  84 static const char *_fVersion;
  85 static jboolean _wc_enabled = JNI_FALSE;
  86 
  87 /*
  88  * Entries for splash screen environment variables.
  89  * putenv is performed in SelectVersion. We need
  90  * them in memory until UnsetEnv, so they are made static
  91  * global instead of auto local.
  92  */
  93 static char* splash_file_entry = NULL;
  94 static char* splash_jar_entry = NULL;
  95 
  96 /*
  97  * List of VM options to be specified when the VM is created.
  98  */
  99 static JavaVMOption *options;
 100 static int numOptions, maxOptions;
 101 
 102 /*
 103  * Prototypes for functions internal to launcher.
 104  */
 105 static void SetClassPath(const char *s);
 106 static void SetMainModule(const char *s);
 107 static void SelectVersion(int argc, char **argv, char **main_class);
 108 static void SetJvmEnvironment(int argc, char **argv);
 109 static jboolean ParseArguments(int *pargc, char ***pargv,
 110                                int *pmode, char **pwhat,
 111                                int *pret, const char *jrepath);
 112 static jboolean InitializeJVM(JavaVM **pvm, JNIEnv **penv,
 113                               InvocationFunctions *ifn);
 114 static jstring NewPlatformString(JNIEnv *env, char *s);
 115 static jclass LoadMainClass(JNIEnv *env, int mode, char *name);
 116 static jclass GetApplicationClass(JNIEnv *env);
 117 
 118 static void TranslateApplicationArgs(int jargc, const char **jargv, int *pargc, char ***pargv);
 119 static jboolean AddApplicationOptions(int cpathc, const char **cpathv);
 120 static void SetApplicationClassPath(const char**);
 121 
 122 static void PrintJavaVersion(JNIEnv *env, jboolean extraLF);
 123 static void PrintUsage(JNIEnv* env, jboolean doXUsage);
 124 static void ShowSettings(JNIEnv* env, char *optString);
 125 static void ShowResolvedModules(JNIEnv* env);
 126 static void ListModules(JNIEnv* env);
 127 static void DescribeModule(JNIEnv* env, char* optString);
 128 static jboolean ValidateModules(JNIEnv* env);
 129 
 130 static void SetPaths(int argc, char **argv);
 131 
 132 static void DumpState();
 133 
 134 enum OptionKind {
 135     LAUNCHER_OPTION = 0,
 136     LAUNCHER_OPTION_WITH_ARGUMENT,
 137     LAUNCHER_MAIN_OPTION,
 138     VM_LONG_OPTION,
 139     VM_LONG_OPTION_WITH_ARGUMENT,
 140     VM_OPTION
 141 };
 142 
 143 static int GetOpt(int *pargc, char ***pargv, char **poption, char **pvalue);
 144 static jboolean IsOptionWithArgument(int argc, char **argv);
 145 
 146 /* Maximum supported entries from jvm.cfg. */
 147 #define INIT_MAX_KNOWN_VMS      10
 148 
 149 /* Values for vmdesc.flag */
 150 enum vmdesc_flag {
 151     VM_UNKNOWN = -1,
 152     VM_KNOWN,
 153     VM_ALIASED_TO,
 154     VM_WARN,
 155     VM_ERROR,
 156     VM_IF_SERVER_CLASS,
 157     VM_IGNORE
 158 };
 159 
 160 struct vmdesc {
 161     char *name;
 162     int flag;
 163     char *alias;
 164     char *server_class;
 165 };
 166 static struct vmdesc *knownVMs = NULL;
 167 static int knownVMsCount = 0;
 168 static int knownVMsLimit = 0;
 169 
 170 static void GrowKnownVMs(int minimum);
 171 static int  KnownVMIndex(const char* name);
 172 static void FreeKnownVMs();
 173 static jboolean IsWildCardEnabled();
 174 
 175 
 176 #define SOURCE_LAUNCHER_MAIN_ENTRY "jdk.compiler/com.sun.tools.javac.launcher.Main"
 177 
 178 /*
 179  * This reports error.  VM will not be created and no usage is printed.
 180  */
 181 #define REPORT_ERROR(AC_ok, AC_failure_message, AC_questionable_arg) \
 182     do { \
 183         if (!AC_ok) { \
 184             JLI_ReportErrorMessage(AC_failure_message, AC_questionable_arg); \
 185             printUsage = JNI_FALSE; \
 186             *pret = 1; \
 187             return JNI_FALSE; \
 188         } \
 189     } while (JNI_FALSE)
 190 
 191 #define ARG_CHECK(AC_arg_count, AC_failure_message, AC_questionable_arg) \
 192     do { \
 193         if (AC_arg_count < 1) { \
 194             JLI_ReportErrorMessage(AC_failure_message, AC_questionable_arg); \
 195             printUsage = JNI_TRUE; \
 196             *pret = 1; \
 197             return JNI_TRUE; \
 198         } \
 199     } while (JNI_FALSE)
 200 
 201 /*
 202  * Running Java code in primordial thread caused many problems. We will
 203  * create a new thread to invoke JVM. See 6316197 for more information.
 204  */
 205 static jlong threadStackSize    = 0;  /* stack size of the new thread */
 206 static jlong maxHeapSize        = 0;  /* max heap size */
 207 static jlong initialHeapSize    = 0;  /* inital heap size */
 208 
 209 /*
 210  * A minimum -Xss stack size suitable for all platforms.
 211  */
 212 #ifndef STACK_SIZE_MINIMUM
 213 #define STACK_SIZE_MINIMUM (64 * KB)
 214 #endif
 215 
 216 /*
 217  * Entry point.
 218  */
 219 JNIEXPORT int JNICALL
 220 JLI_Launch(int argc, char ** argv,              /* main argc, argv */
 221         int jargc, const char** jargv,          /* java args */
 222         int appclassc, const char** appclassv,  /* app classpath */
 223         const char* fullversion,                /* full version defined */
 224         const char* dotversion,                 /* UNUSED dot version defined */
 225         const char* pname,                      /* program name */
 226         const char* lname,                      /* launcher name */
 227         jboolean javaargs,                      /* JAVA_ARGS */
 228         jboolean cpwildcard,                    /* classpath wildcard*/
 229         jboolean javaw,                         /* windows-only javaw */
 230         jint ergo                               /* unused */
 231 )
 232 {
 233     int mode = LM_UNKNOWN;
 234     char *what = NULL;
 235     char *main_class = NULL;
 236     int ret;
 237     InvocationFunctions ifn;
 238     jlong start, end;
 239     char jvmpath[MAXPATHLEN];
 240     char jrepath[MAXPATHLEN];
 241     char jvmcfg[MAXPATHLEN];
 242 
 243     _fVersion = fullversion;
 244     _launcher_name = lname;
 245     _program_name = pname;
 246     _is_java_args = javaargs;
 247     _wc_enabled = cpwildcard;
 248 
 249     InitLauncher(javaw);
 250     DumpState();
 251     if (JLI_IsTraceLauncher()) {
 252         int i;
 253         printf("Java args:\n");
 254         for (i = 0; i < jargc ; i++) {
 255             printf("jargv[%d] = %s\n", i, jargv[i]);
 256         }
 257         printf("Command line args:\n");
 258         for (i = 0; i < argc ; i++) {
 259             printf("argv[%d] = %s\n", i, argv[i]);
 260         }
 261         AddOption("-Dsun.java.launcher.diag=true", NULL);
 262     }
 263 
 264     /*
 265      * SelectVersion() has several responsibilities:
 266      *
 267      *  1) Disallow specification of another JRE.  With 1.9, another
 268      *     version of the JRE cannot be invoked.
 269      *  2) Allow for a JRE version to invoke JDK 1.9 or later.  Since
 270      *     all mJRE directives have been stripped from the request but
 271      *     the pre 1.9 JRE [ 1.6 thru 1.8 ], it is as if 1.9+ has been
 272      *     invoked from the command line.
 273      */
 274     SelectVersion(argc, argv, &main_class);
 275 
 276     CreateExecutionEnvironment(&argc, &argv,
 277                                jrepath, sizeof(jrepath),
 278                                jvmpath, sizeof(jvmpath),
 279                                jvmcfg,  sizeof(jvmcfg));
 280 
 281     if (!IsJavaArgs()) {
 282         SetJvmEnvironment(argc,argv);
 283     }
 284 
 285     ifn.CreateJavaVM = 0;
 286     ifn.GetDefaultJavaVMInitArgs = 0;
 287 
 288     if (JLI_IsTraceLauncher()) {
 289         start = CounterGet();
 290     }
 291 
 292     if (!LoadJavaVM(jvmpath, &ifn)) {
 293         return(6);
 294     }
 295 
 296     if (JLI_IsTraceLauncher()) {
 297         end   = CounterGet();
 298     }
 299 
 300     JLI_TraceLauncher("%ld micro seconds to LoadJavaVM\n",
 301              (long)(jint)Counter2Micros(end-start));
 302 
 303     ++argv;
 304     --argc;
 305 
 306     if (IsJavaArgs()) {
 307         /* Preprocess wrapper arguments */
 308         TranslateApplicationArgs(jargc, jargv, &argc, &argv);
 309         if (!AddApplicationOptions(appclassc, appclassv)) {
 310             return(1);
 311         }
 312     } else {
 313         /* Set default CLASSPATH */
 314         char* cpath = getenv("CLASSPATH");
 315         if (cpath != NULL) {
 316             SetClassPath(cpath);
 317         }
 318     }
 319 
 320     /* Parse command line options; if the return value of
 321      * ParseArguments is false, the program should exit.
 322      */
 323     if (!ParseArguments(&argc, &argv, &mode, &what, &ret, jrepath)) {
 324         return(ret);
 325     }
 326 
 327     /* Override class path if -jar flag was specified */
 328     if (mode == LM_JAR) {
 329         SetClassPath(what);     /* Override class path */
 330     }
 331 
 332     /* set the -Dsun.java.command pseudo property */
 333     SetJavaCommandLineProp(what, argc, argv);
 334 
 335     /* Set the -Dsun.java.launcher pseudo property */
 336     SetJavaLauncherProp();
 337 
 338     /* set the -Dsun.java.launcher.* platform properties */
 339     SetJavaLauncherPlatformProps();
 340 
 341     return JVMInit(&ifn, threadStackSize, argc, argv, mode, what, ret);
 342 }
 343 /*
 344  * Always detach the main thread so that it appears to have ended when
 345  * the application's main method exits.  This will invoke the
 346  * uncaught exception handler machinery if main threw an
 347  * exception.  An uncaught exception handler cannot change the
 348  * launcher's return code except by calling System.exit.
 349  *
 350  * Wait for all non-daemon threads to end, then destroy the VM.
 351  * This will actually create a trivial new Java waiter thread
 352  * named "DestroyJavaVM", but this will be seen as a different
 353  * thread from the one that executed main, even though they are
 354  * the same C thread.  This allows mainThread.join() and
 355  * mainThread.isAlive() to work as expected.
 356  */
 357 #define LEAVE() \
 358     do { \
 359         if ((*vm)->DetachCurrentThread(vm) != JNI_OK) { \
 360             JLI_ReportErrorMessage(JVM_ERROR2); \
 361             ret = 1; \
 362         } \
 363         if (JNI_TRUE) { \
 364             (*vm)->DestroyJavaVM(vm); \
 365             return ret; \
 366         } \
 367     } while (JNI_FALSE)
 368 
 369 #define CHECK_EXCEPTION_NULL_LEAVE(CENL_exception) \
 370     do { \
 371         if ((*env)->ExceptionOccurred(env)) { \
 372             JLI_ReportExceptionDescription(env); \
 373             LEAVE(); \
 374         } \
 375         if ((CENL_exception) == NULL) { \
 376             JLI_ReportErrorMessage(JNI_ERROR); \
 377             LEAVE(); \
 378         } \
 379     } while (JNI_FALSE)
 380 
 381 #define CHECK_EXCEPTION_LEAVE(CEL_return_value) \
 382     do { \
 383         if ((*env)->ExceptionOccurred(env)) { \
 384             JLI_ReportExceptionDescription(env); \
 385             ret = (CEL_return_value); \
 386             LEAVE(); \
 387         } \
 388     } while (JNI_FALSE)
 389 
 390 
 391 int JNICALL
 392 JavaMain(void * _args)
 393 {
 394     JavaMainArgs *args = (JavaMainArgs *)_args;
 395     int argc = args->argc;
 396     char **argv = args->argv;
 397     int mode = args->mode;
 398     char *what = args->what;
 399     InvocationFunctions ifn = args->ifn;
 400 
 401     JavaVM *vm = 0;
 402     JNIEnv *env = 0;
 403     jclass mainClass = NULL;
 404     jclass appClass = NULL; // actual application class being launched
 405     jmethodID mainID;
 406     jobjectArray mainArgs;
 407     int ret = 0;
 408     jlong start, end;
 409 
 410     RegisterThread();
 411 
 412     /* Initialize the virtual machine */
 413     start = CounterGet();
 414     if (!InitializeJVM(&vm, &env, &ifn)) {
 415         JLI_ReportErrorMessage(JVM_ERROR1);
 416         exit(1);
 417     }
 418 
 419     if (showSettings != NULL) {
 420         ShowSettings(env, showSettings);
 421         CHECK_EXCEPTION_LEAVE(1);
 422     }
 423 
 424     // show resolved modules and continue
 425     if (showResolvedModules) {
 426         ShowResolvedModules(env);
 427         CHECK_EXCEPTION_LEAVE(1);
 428     }
 429 
 430     // list observable modules, then exit
 431     if (listModules) {
 432         ListModules(env);
 433         CHECK_EXCEPTION_LEAVE(1);
 434         LEAVE();
 435     }
 436 
 437     // describe a module, then exit
 438     if (describeModule != NULL) {
 439         DescribeModule(env, describeModule);
 440         CHECK_EXCEPTION_LEAVE(1);
 441         LEAVE();
 442     }
 443 
 444     if (printVersion || showVersion) {
 445         PrintJavaVersion(env, showVersion);
 446         CHECK_EXCEPTION_LEAVE(0);
 447         if (printVersion) {
 448             LEAVE();
 449         }
 450     }
 451 
 452     // modules have been validated at startup so exit
 453     if (validateModules) {
 454         LEAVE();
 455     }
 456 
 457     /* If the user specified neither a class name nor a JAR file */
 458     if (printXUsage || printUsage || what == 0 || mode == LM_UNKNOWN) {
 459         PrintUsage(env, printXUsage);
 460         CHECK_EXCEPTION_LEAVE(1);
 461         LEAVE();
 462     }
 463 
 464     FreeKnownVMs(); /* after last possible PrintUsage */
 465 
 466     if (JLI_IsTraceLauncher()) {
 467         end = CounterGet();
 468         JLI_TraceLauncher("%ld micro seconds to InitializeJVM\n",
 469                (long)(jint)Counter2Micros(end-start));
 470     }
 471 
 472     /* At this stage, argc/argv have the application's arguments */
 473     if (JLI_IsTraceLauncher()){
 474         int i;
 475         printf("%s is '%s'\n", launchModeNames[mode], what);
 476         printf("App's argc is %d\n", argc);
 477         for (i=0; i < argc; i++) {
 478             printf("    argv[%2d] = '%s'\n", i, argv[i]);
 479         }
 480     }
 481 
 482     ret = 1;
 483 
 484     /*
 485      * Get the application's main class. It also checks if the main
 486      * method exists.
 487      *
 488      * See bugid 5030265.  The Main-Class name has already been parsed
 489      * from the manifest, but not parsed properly for UTF-8 support.
 490      * Hence the code here ignores the value previously extracted and
 491      * uses the pre-existing code to reextract the value.  This is
 492      * possibly an end of release cycle expedient.  However, it has
 493      * also been discovered that passing some character sets through
 494      * the environment has "strange" behavior on some variants of
 495      * Windows.  Hence, maybe the manifest parsing code local to the
 496      * launcher should never be enhanced.
 497      *
 498      * Hence, future work should either:
 499      *     1)   Correct the local parsing code and verify that the
 500      *          Main-Class attribute gets properly passed through
 501      *          all environments,
 502      *     2)   Remove the vestages of maintaining main_class through
 503      *          the environment (and remove these comments).
 504      *
 505      * This method also correctly handles launching existing JavaFX
 506      * applications that may or may not have a Main-Class manifest entry.
 507      */
 508     mainClass = LoadMainClass(env, mode, what);
 509     CHECK_EXCEPTION_NULL_LEAVE(mainClass);
 510     /*
 511      * In some cases when launching an application that needs a helper, e.g., a
 512      * JavaFX application with no main method, the mainClass will not be the
 513      * applications own main class but rather a helper class. To keep things
 514      * consistent in the UI we need to track and report the application main class.
 515      */
 516     appClass = GetApplicationClass(env);
 517     NULL_CHECK_RETURN_VALUE(appClass, -1);
 518 
 519     /* Build platform specific argument array */
 520     mainArgs = CreateApplicationArgs(env, argv, argc);
 521     CHECK_EXCEPTION_NULL_LEAVE(mainArgs);
 522 
 523     if (dryRun) {
 524         ret = 0;
 525         LEAVE();
 526     }
 527 
 528     /*
 529      * PostJVMInit uses the class name as the application name for GUI purposes,
 530      * for example, on OSX this sets the application name in the menu bar for
 531      * both SWT and JavaFX. So we'll pass the actual application class here
 532      * instead of mainClass as that may be a launcher or helper class instead
 533      * of the application class.
 534      */
 535     PostJVMInit(env, appClass, vm);
 536     CHECK_EXCEPTION_LEAVE(1);
 537 
 538     /*
 539      * The LoadMainClass not only loads the main class, it will also ensure
 540      * that the main method's signature is correct, therefore further checking
 541      * is not required. The main method is invoked here so that extraneous java
 542      * stacks are not in the application stack trace.
 543      */
 544     mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
 545                                        "([Ljava/lang/String;)V");
 546     CHECK_EXCEPTION_NULL_LEAVE(mainID);
 547 
 548     /* Invoke main method. */
 549     (*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);
 550 
 551     /*
 552      * The launcher's exit code (in the absence of calls to
 553      * System.exit) will be non-zero if main threw an exception.
 554      */
 555     ret = (*env)->ExceptionOccurred(env) == NULL ? 0 : 1;
 556 
 557     LEAVE();
 558 }
 559 
 560 /*
 561  * Test if the given name is one of the class path options.
 562  */
 563 static jboolean
 564 IsClassPathOption(const char* name) {
 565     return JLI_StrCmp(name, "-classpath") == 0 ||
 566            JLI_StrCmp(name, "-cp") == 0 ||
 567            JLI_StrCmp(name, "--class-path") == 0;
 568 }
 569 
 570 /*
 571  * Test if the given name is a launcher option taking the main entry point.
 572  */
 573 static jboolean
 574 IsLauncherMainOption(const char* name) {
 575     return JLI_StrCmp(name, "--module") == 0 ||
 576            JLI_StrCmp(name, "-m") == 0;
 577 }
 578 
 579 /*
 580  * Test if the given name is a white-space launcher option.
 581  */
 582 static jboolean
 583 IsLauncherOption(const char* name) {
 584     return IsClassPathOption(name) ||
 585            IsLauncherMainOption(name) ||
 586            JLI_StrCmp(name, "--describe-module") == 0 ||
 587            JLI_StrCmp(name, "-d") == 0 ||
 588            JLI_StrCmp(name, "--source") == 0;
 589 }
 590 
 591 /*
 592  * Test if the given name is a module-system white-space option that
 593  * will be passed to the VM with its corresponding long-form option
 594  * name and "=" delimiter.
 595  */
 596 static jboolean
 597 IsModuleOption(const char* name) {
 598     return JLI_StrCmp(name, "--module-path") == 0 ||
 599            JLI_StrCmp(name, "-p") == 0 ||
 600            JLI_StrCmp(name, "--upgrade-module-path") == 0 ||
 601            JLI_StrCmp(name, "--add-modules") == 0 ||
 602            JLI_StrCmp(name, "--limit-modules") == 0 ||
 603            JLI_StrCmp(name, "--add-exports") == 0 ||
 604            JLI_StrCmp(name, "--add-opens") == 0 ||
 605            JLI_StrCmp(name, "--add-reads") == 0 ||
 606            JLI_StrCmp(name, "--patch-module") == 0;
 607 }
 608 
 609 static jboolean
 610 IsLongFormModuleOption(const char* name) {
 611     return JLI_StrCCmp(name, "--module-path=") == 0 ||
 612            JLI_StrCCmp(name, "--upgrade-module-path=") == 0 ||
 613            JLI_StrCCmp(name, "--add-modules=") == 0 ||
 614            JLI_StrCCmp(name, "--limit-modules=") == 0 ||
 615            JLI_StrCCmp(name, "--add-exports=") == 0 ||
 616            JLI_StrCCmp(name, "--add-reads=") == 0 ||
 617            JLI_StrCCmp(name, "--patch-module=") == 0;
 618 }
 619 
 620 /*
 621  * Test if the given name has a white space option.
 622  */
 623 jboolean
 624 IsWhiteSpaceOption(const char* name) {
 625     return IsModuleOption(name) ||
 626            IsLauncherOption(name);
 627 }
 628 
 629 /*
 630  * Check if it is OK to set the mode.
 631  * If the mode was previously set, and should not be changed,
 632  * a fatal error is reported.
 633  */
 634 static int
 635 checkMode(int mode, int newMode, const char *arg) {
 636     if (mode == LM_SOURCE) {
 637         JLI_ReportErrorMessage(ARG_ERROR14, arg);
 638         exit(1);
 639     }
 640     return newMode;
 641 }
 642 
 643 /*
 644  * Test if an arg identifies a source file.
 645  */
 646 jboolean
 647 IsSourceFile(const char *arg) {
 648     struct stat st;
 649     return (JLI_HasSuffix(arg, ".java") && stat(arg, &st) == 0);
 650 }
 651 
 652 /*
 653  * Checks the command line options to find which JVM type was
 654  * specified.  If no command line option was given for the JVM type,
 655  * the default type is used.  The environment variable
 656  * JDK_ALTERNATE_VM and the command line option -XXaltjvm= are also
 657  * checked as ways of specifying which JVM type to invoke.
 658  */
 659 char *
 660 CheckJvmType(int *pargc, char ***argv, jboolean speculative) {
 661     int i, argi;
 662     int argc;
 663     char **newArgv;
 664     int newArgvIdx = 0;
 665     int isVMType;
 666     int jvmidx = -1;
 667     char *jvmtype = getenv("JDK_ALTERNATE_VM");
 668 
 669     argc = *pargc;
 670 
 671     /* To make things simpler we always copy the argv array */
 672     newArgv = JLI_MemAlloc((argc + 1) * sizeof(char *));
 673 
 674     /* The program name is always present */
 675     newArgv[newArgvIdx++] = (*argv)[0];
 676 
 677     for (argi = 1; argi < argc; argi++) {
 678         char *arg = (*argv)[argi];
 679         isVMType = 0;
 680 
 681         if (IsJavaArgs()) {
 682             if (arg[0] != '-') {
 683                 newArgv[newArgvIdx++] = arg;
 684                 continue;
 685             }
 686         } else {
 687             if (IsWhiteSpaceOption(arg)) {
 688                 newArgv[newArgvIdx++] = arg;
 689                 argi++;
 690                 if (argi < argc) {
 691                     newArgv[newArgvIdx++] = (*argv)[argi];
 692                 }
 693                 continue;
 694             }
 695             if (arg[0] != '-') break;
 696         }
 697 
 698         /* Did the user pass an explicit VM type? */
 699         i = KnownVMIndex(arg);
 700         if (i >= 0) {
 701             jvmtype = knownVMs[jvmidx = i].name + 1; /* skip the - */
 702             isVMType = 1;
 703             *pargc = *pargc - 1;
 704         }
 705 
 706         /* Did the user specify an "alternate" VM? */
 707         else if (JLI_StrCCmp(arg, "-XXaltjvm=") == 0 || JLI_StrCCmp(arg, "-J-XXaltjvm=") == 0) {
 708             isVMType = 1;
 709             jvmtype = arg+((arg[1]=='X')? 10 : 12);
 710             jvmidx = -1;
 711         }
 712 
 713         if (!isVMType) {
 714             newArgv[newArgvIdx++] = arg;
 715         }
 716     }
 717 
 718     /*
 719      * Finish copying the arguments if we aborted the above loop.
 720      * NOTE that if we aborted via "break" then we did NOT copy the
 721      * last argument above, and in addition argi will be less than
 722      * argc.
 723      */
 724     while (argi < argc) {
 725         newArgv[newArgvIdx++] = (*argv)[argi];
 726         argi++;
 727     }
 728 
 729     /* argv is null-terminated */
 730     newArgv[newArgvIdx] = 0;
 731 
 732     /* Copy back argv */
 733     *argv = newArgv;
 734     *pargc = newArgvIdx;
 735 
 736     /* use the default VM type if not specified (no alias processing) */
 737     if (jvmtype == NULL) {
 738       char* result = knownVMs[0].name+1;
 739       JLI_TraceLauncher("Default VM: %s\n", result);
 740       return result;
 741     }
 742 
 743     /* if using an alternate VM, no alias processing */
 744     if (jvmidx < 0)
 745       return jvmtype;
 746 
 747     /* Resolve aliases first */
 748     {
 749       int loopCount = 0;
 750       while (knownVMs[jvmidx].flag == VM_ALIASED_TO) {
 751         int nextIdx = KnownVMIndex(knownVMs[jvmidx].alias);
 752 
 753         if (loopCount > knownVMsCount) {
 754           if (!speculative) {
 755             JLI_ReportErrorMessage(CFG_ERROR1);
 756             exit(1);
 757           } else {
 758             return "ERROR";
 759             /* break; */
 760           }
 761         }
 762 
 763         if (nextIdx < 0) {
 764           if (!speculative) {
 765             JLI_ReportErrorMessage(CFG_ERROR2, knownVMs[jvmidx].alias);
 766             exit(1);
 767           } else {
 768             return "ERROR";
 769           }
 770         }
 771         jvmidx = nextIdx;
 772         jvmtype = knownVMs[jvmidx].name+1;
 773         loopCount++;
 774       }
 775     }
 776 
 777     switch (knownVMs[jvmidx].flag) {
 778     case VM_WARN:
 779         if (!speculative) {
 780             JLI_ReportErrorMessage(CFG_WARN1, jvmtype, knownVMs[0].name + 1);
 781         }
 782         /* fall through */
 783     case VM_IGNORE:
 784         jvmtype = knownVMs[jvmidx=0].name + 1;
 785         /* fall through */
 786     case VM_KNOWN:
 787         break;
 788     case VM_ERROR:
 789         if (!speculative) {
 790             JLI_ReportErrorMessage(CFG_ERROR3, jvmtype);
 791             exit(1);
 792         } else {
 793             return "ERROR";
 794         }
 795     }
 796 
 797     return jvmtype;
 798 }
 799 
 800 /*
 801  * This method must be called before the VM is loaded, primarily
 802  * used to parse and set any VM related options or env variables.
 803  * This function is non-destructive leaving the argument list intact.
 804  */
 805 static void
 806 SetJvmEnvironment(int argc, char **argv) {
 807 
 808     static const char*  NMT_Env_Name    = "NMT_LEVEL_";
 809     int i;
 810     /* process only the launcher arguments */
 811     for (i = 0; i < argc; i++) {
 812         char *arg = argv[i];
 813         /*
 814          * Since this must be a VM flag we stop processing once we see
 815          * an argument the launcher would not have processed beyond (such
 816          * as -version or -h), or an argument that indicates the following
 817          * arguments are for the application (i.e. the main class name, or
 818          * the -jar argument).
 819          */
 820         if (i > 0) {
 821             char *prev = argv[i - 1];
 822             // skip non-dash arg preceded by class path specifiers
 823             if (*arg != '-' && IsWhiteSpaceOption(prev)) {
 824                 continue;
 825             }
 826 
 827             if (*arg != '-' || isTerminalOpt(arg)) {
 828                 return;
 829             }
 830         }
 831         /*
 832          * The following case checks for "-XX:NativeMemoryTracking=value".
 833          * If value is non null, an environmental variable set to this value
 834          * will be created to be used by the JVM.
 835          * The argument is passed to the JVM, which will check validity.
 836          * The JVM is responsible for removing the env variable.
 837          */
 838         if (JLI_StrCCmp(arg, "-XX:NativeMemoryTracking=") == 0) {
 839             int retval;
 840             // get what follows this parameter, include "="
 841             size_t pnlen = JLI_StrLen("-XX:NativeMemoryTracking=");
 842             if (JLI_StrLen(arg) > pnlen) {
 843                 char* value = arg + pnlen;
 844                 size_t pbuflen = pnlen + JLI_StrLen(value) + 10; // 10 max pid digits
 845 
 846                 /*
 847                  * ensures that malloc successful
 848                  * DONT JLI_MemFree() pbuf.  JLI_PutEnv() uses system call
 849                  *   that could store the address.
 850                  */
 851                 char * pbuf = (char*)JLI_MemAlloc(pbuflen);
 852 
 853                 JLI_Snprintf(pbuf, pbuflen, "%s%d=%s", NMT_Env_Name, JLI_GetPid(), value);
 854                 retval = JLI_PutEnv(pbuf);
 855                 if (JLI_IsTraceLauncher()) {
 856                     char* envName;
 857                     char* envBuf;
 858 
 859                     // ensures that malloc successful
 860                     envName = (char*)JLI_MemAlloc(pbuflen);
 861                     JLI_Snprintf(envName, pbuflen, "%s%d", NMT_Env_Name, JLI_GetPid());
 862 
 863                     printf("TRACER_MARKER: NativeMemoryTracking: env var is %s\n",envName);
 864                     printf("TRACER_MARKER: NativeMemoryTracking: putenv arg %s\n",pbuf);
 865                     envBuf = getenv(envName);
 866                     printf("TRACER_MARKER: NativeMemoryTracking: got value %s\n",envBuf);
 867                     free(envName);
 868                 }
 869             }
 870         }
 871     }
 872 }
 873 
 874 /* copied from HotSpot function "atomll()" */
 875 static int
 876 parse_size(const char *s, jlong *result) {
 877   jlong n = 0;
 878   int args_read = sscanf(s, JLONG_FORMAT_SPECIFIER, &n);
 879   if (args_read != 1) {
 880     return 0;
 881   }
 882   while (*s != '\0' && *s >= '0' && *s <= '9') {
 883     s++;
 884   }
 885   // 4705540: illegal if more characters are found after the first non-digit
 886   if (JLI_StrLen(s) > 1) {
 887     return 0;
 888   }
 889   switch (*s) {
 890     case 'T': case 't':
 891       *result = n * GB * KB;
 892       return 1;
 893     case 'G': case 'g':
 894       *result = n * GB;
 895       return 1;
 896     case 'M': case 'm':
 897       *result = n * MB;
 898       return 1;
 899     case 'K': case 'k':
 900       *result = n * KB;
 901       return 1;
 902     case '\0':
 903       *result = n;
 904       return 1;
 905     default:
 906       /* Create JVM with default stack and let VM handle malformed -Xss string*/
 907       return 0;
 908   }
 909 }
 910 
 911 /*
 912  * Adds a new VM option with the given name and value.
 913  */
 914 void
 915 AddOption(char *str, void *info)
 916 {
 917     /*
 918      * Expand options array if needed to accommodate at least one more
 919      * VM option.
 920      */
 921     if (numOptions >= maxOptions) {
 922         if (options == 0) {
 923             maxOptions = 4;
 924             options = JLI_MemAlloc(maxOptions * sizeof(JavaVMOption));
 925         } else {
 926             JavaVMOption *tmp;
 927             maxOptions *= 2;
 928             tmp = JLI_MemAlloc(maxOptions * sizeof(JavaVMOption));
 929             memcpy(tmp, options, numOptions * sizeof(JavaVMOption));
 930             JLI_MemFree(options);
 931             options = tmp;
 932         }
 933     }
 934     options[numOptions].optionString = str;
 935     options[numOptions++].extraInfo = info;
 936 
 937     if (JLI_StrCCmp(str, "-Xss") == 0) {
 938         jlong tmp;
 939         if (parse_size(str + 4, &tmp)) {
 940             threadStackSize = tmp;
 941             /*
 942              * Make sure the thread stack size is big enough that we won't get a stack
 943              * overflow before the JVM startup code can check to make sure the stack
 944              * is big enough.
 945              */
 946             if (threadStackSize < (jlong)STACK_SIZE_MINIMUM) {
 947                 threadStackSize = STACK_SIZE_MINIMUM;
 948             }
 949         }
 950     }
 951 
 952     if (JLI_StrCCmp(str, "-Xmx") == 0) {
 953         jlong tmp;
 954         if (parse_size(str + 4, &tmp)) {
 955             maxHeapSize = tmp;
 956         }
 957     }
 958 
 959     if (JLI_StrCCmp(str, "-Xms") == 0) {
 960         jlong tmp;
 961         if (parse_size(str + 4, &tmp)) {
 962            initialHeapSize = tmp;
 963         }
 964     }
 965 }
 966 
 967 static void
 968 SetClassPath(const char *s)
 969 {
 970     char *def;
 971     const char *orig = s;
 972     static const char format[] = "-Djava.class.path=%s";
 973     /*
 974      * usually we should not get a null pointer, but there are cases where
 975      * we might just get one, in which case we simply ignore it, and let the
 976      * caller deal with it
 977      */
 978     if (s == NULL)
 979         return;
 980     s = JLI_WildcardExpandClasspath(s);
 981     if (sizeof(format) - 2 + JLI_StrLen(s) < JLI_StrLen(s))
 982         // s is became corrupted after expanding wildcards
 983         return;
 984     def = JLI_MemAlloc(sizeof(format)
 985                        - 2 /* strlen("%s") */
 986                        + JLI_StrLen(s));
 987     sprintf(def, format, s);
 988     AddOption(def, NULL);
 989     if (s != orig)
 990         JLI_MemFree((char *) s);
 991     _have_classpath = JNI_TRUE;
 992 }
 993 
 994 static void
 995 AddLongFormOption(const char *option, const char *arg)
 996 {
 997     static const char format[] = "%s=%s";
 998     char *def;
 999     size_t def_len;
1000 
1001     def_len = JLI_StrLen(option) + 1 + JLI_StrLen(arg) + 1;
1002     def = JLI_MemAlloc(def_len);
1003     JLI_Snprintf(def, def_len, format, option, arg);
1004     AddOption(def, NULL);
1005 }
1006 
1007 static void
1008 SetMainModule(const char *s)
1009 {
1010     static const char format[] = "-Djdk.module.main=%s";
1011     char* slash = JLI_StrChr(s, '/');
1012     size_t s_len, def_len;
1013     char *def;
1014 
1015     /* value may be <module> or <module>/<mainclass> */
1016     if (slash == NULL) {
1017         s_len = JLI_StrLen(s);
1018     } else {
1019         s_len = (size_t) (slash - s);
1020     }
1021     def_len = sizeof(format)
1022                - 2 /* strlen("%s") */
1023                + s_len;
1024     def = JLI_MemAlloc(def_len);
1025     JLI_Snprintf(def, def_len, format, s);
1026     AddOption(def, NULL);
1027 }
1028 
1029 /*
1030  * The SelectVersion() routine ensures that an appropriate version of
1031  * the JRE is running.  The specification for the appropriate version
1032  * is obtained from either the manifest of a jar file (preferred) or
1033  * from command line options.
1034  * The routine also parses splash screen command line options and
1035  * passes on their values in private environment variables.
1036  */
1037 static void
1038 SelectVersion(int argc, char **argv, char **main_class)
1039 {
1040     char    *arg;
1041     char    *operand;
1042     char    *version = NULL;
1043     char    *jre = NULL;
1044     int     jarflag = 0;
1045     int     headlessflag = 0;
1046     int     restrict_search = -1;               /* -1 implies not known */
1047     manifest_info info;
1048     char    env_entry[MAXNAMELEN + 24] = ENV_ENTRY "=";
1049     char    *splash_file_name = NULL;
1050     char    *splash_jar_name = NULL;
1051     char    *env_in;
1052     int     res;
1053     jboolean has_arg;
1054 
1055     /*
1056      * If the version has already been selected, set *main_class
1057      * with the value passed through the environment (if any) and
1058      * simply return.
1059      */
1060 
1061     /*
1062      * This environmental variable can be set by mJRE capable JREs
1063      * [ 1.5 thru 1.8 ].  All other aspects of mJRE processing have been
1064      * stripped by those JREs.  This environmental variable allows 1.9+
1065      * JREs to be started by these mJRE capable JREs.
1066      * Note that mJRE directives in the jar manifest file would have been
1067      * ignored for a JRE started by another JRE...
1068      * .. skipped for JRE 1.5 and beyond.
1069      * .. not even checked for pre 1.5.
1070      */
1071     if ((env_in = getenv(ENV_ENTRY)) != NULL) {
1072         if (*env_in != '\0')
1073             *main_class = JLI_StringDup(env_in);
1074         return;
1075     }
1076 
1077     /*
1078      * Scan through the arguments for options relevant to multiple JRE
1079      * support.  Multiple JRE support existed in JRE versions 1.5 thru 1.8.
1080      *
1081      * This capability is no longer available with JRE versions 1.9 and later.
1082      * These command line options are reported as errors.
1083      */
1084 
1085     argc--;
1086     argv++;
1087     while ((arg = *argv) != 0 && *arg == '-') {
1088         has_arg = IsOptionWithArgument(argc, argv);
1089         if (JLI_StrCCmp(arg, "-version:") == 0) {
1090             JLI_ReportErrorMessage(SPC_ERROR1);
1091         } else if (JLI_StrCmp(arg, "-jre-restrict-search") == 0) {
1092             JLI_ReportErrorMessage(SPC_ERROR2);
1093         } else if (JLI_StrCmp(arg, "-jre-no-restrict-search") == 0) {
1094             JLI_ReportErrorMessage(SPC_ERROR2);
1095         } else {
1096             if (JLI_StrCmp(arg, "-jar") == 0)
1097                 jarflag = 1;
1098             if (IsWhiteSpaceOption(arg)) {
1099                 if (has_arg) {
1100                     argc--;
1101                     argv++;
1102                     arg = *argv;
1103                 }
1104             }
1105 
1106             /*
1107              * Checking for headless toolkit option in the some way as AWT does:
1108              * "true" means true and any other value means false
1109              */
1110             if (JLI_StrCmp(arg, "-Djava.awt.headless=true") == 0) {
1111                 headlessflag = 1;
1112             } else if (JLI_StrCCmp(arg, "-Djava.awt.headless=") == 0) {
1113                 headlessflag = 0;
1114             } else if (JLI_StrCCmp(arg, "-splash:") == 0) {
1115                 splash_file_name = arg+8;
1116             }
1117         }
1118         argc--;
1119         argv++;
1120     }
1121     if (argc <= 0) {    /* No operand? Possibly legit with -[full]version */
1122         operand = NULL;
1123     } else {
1124         argc--;
1125         operand = *argv++;
1126     }
1127 
1128     /*
1129      * If there is a jar file, read the manifest. If the jarfile can't be
1130      * read, the manifest can't be read from the jar file, or the manifest
1131      * is corrupt, issue the appropriate error messages and exit.
1132      *
1133      * Even if there isn't a jar file, construct a manifest_info structure
1134      * containing the command line information.  It's a convenient way to carry
1135      * this data around.
1136      */
1137     if (jarflag && operand) {
1138         if ((res = JLI_ParseManifest(operand, &info)) != 0) {
1139             if (res == -1)
1140                 JLI_ReportErrorMessage(JAR_ERROR2, operand);
1141             else
1142                 JLI_ReportErrorMessage(JAR_ERROR3, operand);
1143             exit(1);
1144         }
1145 
1146         /*
1147          * Command line splash screen option should have precedence
1148          * over the manifest, so the manifest data is used only if
1149          * splash_file_name has not been initialized above during command
1150          * line parsing
1151          */
1152         if (!headlessflag && !splash_file_name && info.splashscreen_image_file_name) {
1153             splash_file_name = info.splashscreen_image_file_name;
1154             splash_jar_name = operand;
1155         }
1156     } else {
1157         info.manifest_version = NULL;
1158         info.main_class = NULL;
1159         info.jre_version = NULL;
1160         info.jre_restrict_search = 0;
1161     }
1162 
1163     /*
1164      * Passing on splash screen info in environment variables
1165      */
1166     if (splash_file_name && !headlessflag) {
1167         char* splash_file_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_FILE_ENV_ENTRY "=")+JLI_StrLen(splash_file_name)+1);
1168         JLI_StrCpy(splash_file_entry, SPLASH_FILE_ENV_ENTRY "=");
1169         JLI_StrCat(splash_file_entry, splash_file_name);
1170         putenv(splash_file_entry);
1171     }
1172     if (splash_jar_name && !headlessflag) {
1173         char* splash_jar_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_JAR_ENV_ENTRY "=")+JLI_StrLen(splash_jar_name)+1);
1174         JLI_StrCpy(splash_jar_entry, SPLASH_JAR_ENV_ENTRY "=");
1175         JLI_StrCat(splash_jar_entry, splash_jar_name);
1176         putenv(splash_jar_entry);
1177     }
1178 
1179 
1180     /*
1181      * "Valid" returns (other than unrecoverable errors) follow.  Set
1182      * main_class as a side-effect of this routine.
1183      */
1184     if (info.main_class != NULL)
1185         *main_class = JLI_StringDup(info.main_class);
1186 
1187     if (info.jre_version == NULL) {
1188         JLI_FreeManifest();
1189         return;
1190     }
1191 
1192 }
1193 
1194 /*
1195  * Test if the current argv is an option, i.e. with a leading `-`
1196  * and followed with an argument without a leading `-`.
1197  */
1198 static jboolean
1199 IsOptionWithArgument(int argc, char** argv) {
1200     char* option;
1201     char* arg;
1202 
1203     if (argc <= 1)
1204         return JNI_FALSE;
1205 
1206     option = *argv;
1207     arg = *(argv+1);
1208     return *option == '-' && *arg != '-';
1209 }
1210 
1211 /*
1212  * Gets the option, and its argument if the option has an argument.
1213  * It will update *pargc, **pargv to the next option.
1214  */
1215 static int
1216 GetOpt(int *pargc, char ***pargv, char **poption, char **pvalue) {
1217     int argc = *pargc;
1218     char** argv = *pargv;
1219     char* arg = *argv;
1220 
1221     char* option = arg;
1222     char* value = NULL;
1223     char* equals = NULL;
1224     int kind = LAUNCHER_OPTION;
1225     jboolean has_arg = JNI_FALSE;
1226 
1227     // check if this option may be a white-space option with an argument
1228     has_arg = IsOptionWithArgument(argc, argv);
1229 
1230     argv++; --argc;
1231     if (IsLauncherOption(arg)) {
1232         if (has_arg) {
1233             value = *argv;
1234             argv++; --argc;
1235         }
1236         kind = IsLauncherMainOption(arg) ? LAUNCHER_MAIN_OPTION
1237                                          : LAUNCHER_OPTION_WITH_ARGUMENT;
1238     } else if (IsModuleOption(arg)) {
1239         kind = VM_LONG_OPTION_WITH_ARGUMENT;
1240         if (has_arg) {
1241             value = *argv;
1242             argv++; --argc;
1243         }
1244 
1245         /*
1246          * Support short form alias
1247          */
1248         if (JLI_StrCmp(arg, "-p") == 0) {
1249             option = "--module-path";
1250         }
1251 
1252     } else if (JLI_StrCCmp(arg, "--") == 0 && (equals = JLI_StrChr(arg, '=')) != NULL) {
1253         value = equals+1;
1254         if (JLI_StrCCmp(arg, "--describe-module=") == 0 ||
1255             JLI_StrCCmp(arg, "--module=") == 0 ||
1256             JLI_StrCCmp(arg, "--class-path=") == 0||
1257             JLI_StrCCmp(arg, "--source=") == 0) {
1258             kind = LAUNCHER_OPTION_WITH_ARGUMENT;
1259         } else {
1260             kind = VM_LONG_OPTION;
1261         }
1262     }
1263 
1264     *pargc = argc;
1265     *pargv = argv;
1266     *poption = option;
1267     *pvalue = value;
1268     return kind;
1269 }
1270 
1271 /*
1272  * Parses command line arguments.  Returns JNI_FALSE if launcher
1273  * should exit without starting vm, returns JNI_TRUE if vm needs
1274  * to be started to process given options.  *pret (the launcher
1275  * process return value) is set to 0 for a normal exit.
1276  */
1277 static jboolean
1278 ParseArguments(int *pargc, char ***pargv,
1279                int *pmode, char **pwhat,
1280                int *pret, const char *jrepath)
1281 {
1282     int argc = *pargc;
1283     char **argv = *pargv;
1284     int mode = LM_UNKNOWN;
1285     char *arg;
1286 
1287     *pret = 0;
1288 
1289     while ((arg = *argv) != 0 && *arg == '-') {
1290         char *option = NULL;
1291         char *value = NULL;
1292         int kind = GetOpt(&argc, &argv, &option, &value);
1293         jboolean has_arg = value != NULL && JLI_StrLen(value) > 0;
1294         jboolean has_arg_any_len = value != NULL;
1295 
1296 /*
1297  * Option to set main entry point
1298  */
1299         if (JLI_StrCmp(arg, "-jar") == 0) {
1300             ARG_CHECK(argc, ARG_ERROR2, arg);
1301             mode = checkMode(mode, LM_JAR, arg);
1302         } else if (JLI_StrCmp(arg, "--module") == 0 ||
1303                    JLI_StrCCmp(arg, "--module=") == 0 ||
1304                    JLI_StrCmp(arg, "-m") == 0) {
1305             REPORT_ERROR (has_arg, ARG_ERROR5, arg);
1306             SetMainModule(value);
1307             mode = checkMode(mode, LM_MODULE, arg);
1308             if (has_arg) {
1309                *pwhat = value;
1310                 break;
1311             }
1312         } else if (JLI_StrCmp(arg, "--source") == 0 ||
1313                    JLI_StrCCmp(arg, "--source=") == 0) {
1314             REPORT_ERROR (has_arg, ARG_ERROR13, arg);
1315             mode = LM_SOURCE;
1316             if (has_arg) {
1317                 const char *prop = "-Djdk.internal.javac.source=";
1318                 size_t size = JLI_StrLen(prop) + JLI_StrLen(value) + 1;
1319                 char *propValue = (char *)JLI_MemAlloc(size);
1320                 JLI_Snprintf(propValue, size, "%s%s", prop, value);
1321                 AddOption(propValue, NULL);
1322             }
1323         } else if (JLI_StrCmp(arg, "--class-path") == 0 ||
1324                    JLI_StrCCmp(arg, "--class-path=") == 0 ||
1325                    JLI_StrCmp(arg, "-classpath") == 0 ||
1326                    JLI_StrCmp(arg, "-cp") == 0) {
1327             REPORT_ERROR (has_arg_any_len, ARG_ERROR1, arg);
1328             SetClassPath(value);
1329             mode = LM_CLASS;
1330         } else if (JLI_StrCmp(arg, "--list-modules") == 0) {
1331             listModules = JNI_TRUE;
1332         } else if (JLI_StrCmp(arg, "--show-resolved-modules") == 0) {
1333             showResolvedModules = JNI_TRUE;
1334         } else if (JLI_StrCmp(arg, "--validate-modules") == 0) {
1335             AddOption("-Djdk.module.validation=true", NULL);
1336             validateModules = JNI_TRUE;
1337         } else if (JLI_StrCmp(arg, "--describe-module") == 0 ||
1338                    JLI_StrCCmp(arg, "--describe-module=") == 0 ||
1339                    JLI_StrCmp(arg, "-d") == 0) {
1340             REPORT_ERROR (has_arg_any_len, ARG_ERROR12, arg);
1341             describeModule = value;
1342 /*
1343  * Parse white-space options
1344  */
1345         } else if (has_arg) {
1346             if (kind == VM_LONG_OPTION) {
1347                 AddOption(option, NULL);
1348             } else if (kind == VM_LONG_OPTION_WITH_ARGUMENT) {
1349                 AddLongFormOption(option, value);
1350             }
1351 /*
1352  * Error missing argument
1353  */
1354         } else if (!has_arg && (JLI_StrCmp(arg, "--module-path") == 0 ||
1355                                 JLI_StrCmp(arg, "-p") == 0 ||
1356                                 JLI_StrCmp(arg, "--upgrade-module-path") == 0)) {
1357             REPORT_ERROR (has_arg, ARG_ERROR4, arg);
1358 
1359         } else if (!has_arg && (IsModuleOption(arg) || IsLongFormModuleOption(arg))) {
1360             REPORT_ERROR (has_arg, ARG_ERROR6, arg);
1361 /*
1362  * The following cases will cause the argument parsing to stop
1363  */
1364         } else if (JLI_StrCmp(arg, "-help") == 0 ||
1365                    JLI_StrCmp(arg, "-h") == 0 ||
1366                    JLI_StrCmp(arg, "-?") == 0) {
1367             printUsage = JNI_TRUE;
1368             return JNI_TRUE;
1369         } else if (JLI_StrCmp(arg, "--help") == 0) {
1370             printUsage = JNI_TRUE;
1371             printTo = USE_STDOUT;
1372             return JNI_TRUE;
1373         } else if (JLI_StrCmp(arg, "-version") == 0) {
1374             printVersion = JNI_TRUE;
1375             return JNI_TRUE;
1376         } else if (JLI_StrCmp(arg, "--version") == 0) {
1377             printVersion = JNI_TRUE;
1378             printTo = USE_STDOUT;
1379             return JNI_TRUE;
1380         } else if (JLI_StrCmp(arg, "-showversion") == 0) {
1381             showVersion = JNI_TRUE;
1382         } else if (JLI_StrCmp(arg, "--show-version") == 0) {
1383             showVersion = JNI_TRUE;
1384             printTo = USE_STDOUT;
1385         } else if (JLI_StrCmp(arg, "--dry-run") == 0) {
1386             dryRun = JNI_TRUE;
1387         } else if (JLI_StrCmp(arg, "-X") == 0) {
1388             printXUsage = JNI_TRUE;
1389             return JNI_TRUE;
1390         } else if (JLI_StrCmp(arg, "--help-extra") == 0) {
1391             printXUsage = JNI_TRUE;
1392             printTo = USE_STDOUT;
1393             return JNI_TRUE;
1394 /*
1395  * The following case checks for -XshowSettings OR -XshowSetting:SUBOPT.
1396  * In the latter case, any SUBOPT value not recognized will default to "all"
1397  */
1398         } else if (JLI_StrCmp(arg, "-XshowSettings") == 0 ||
1399                    JLI_StrCCmp(arg, "-XshowSettings:") == 0) {
1400             showSettings = arg;
1401         } else if (JLI_StrCmp(arg, "-Xdiag") == 0) {
1402             AddOption("-Dsun.java.launcher.diag=true", NULL);
1403         } else if (JLI_StrCmp(arg, "--show-module-resolution") == 0) {
1404             AddOption("-Djdk.module.showModuleResolution=true", NULL);
1405 /*
1406  * The following case provide backward compatibility with old-style
1407  * command line options.
1408  */
1409         } else if (JLI_StrCmp(arg, "-fullversion") == 0) {
1410             JLI_ReportMessage("%s full version \"%s\"", _launcher_name, GetFullVersion());
1411             return JNI_FALSE;
1412         } else if (JLI_StrCmp(arg, "--full-version") == 0) {
1413             JLI_ShowMessage("%s %s", _launcher_name, GetFullVersion());
1414             return JNI_FALSE;
1415         } else if (JLI_StrCmp(arg, "-verbosegc") == 0) {
1416             AddOption("-verbose:gc", NULL);
1417         } else if (JLI_StrCmp(arg, "-t") == 0) {
1418             AddOption("-Xt", NULL);
1419         } else if (JLI_StrCmp(arg, "-tm") == 0) {
1420             AddOption("-Xtm", NULL);
1421         } else if (JLI_StrCmp(arg, "-debug") == 0) {
1422             AddOption("-Xdebug", NULL);
1423         } else if (JLI_StrCmp(arg, "-noclassgc") == 0) {
1424             AddOption("-Xnoclassgc", NULL);
1425         } else if (JLI_StrCmp(arg, "-Xfuture") == 0) {
1426             AddOption("-Xverify:all", NULL);
1427         } else if (JLI_StrCmp(arg, "-verify") == 0) {
1428             AddOption("-Xverify:all", NULL);
1429         } else if (JLI_StrCmp(arg, "-verifyremote") == 0) {
1430             AddOption("-Xverify:remote", NULL);
1431         } else if (JLI_StrCmp(arg, "-noverify") == 0) {
1432             AddOption("-Xverify:none", NULL);
1433         } else if (JLI_StrCCmp(arg, "-ss") == 0 ||
1434                    JLI_StrCCmp(arg, "-oss") == 0 ||
1435                    JLI_StrCCmp(arg, "-ms") == 0 ||
1436                    JLI_StrCCmp(arg, "-mx") == 0) {
1437             char *tmp = JLI_MemAlloc(JLI_StrLen(arg) + 6);
1438             sprintf(tmp, "-X%s", arg + 1); /* skip '-' */
1439             AddOption(tmp, NULL);
1440         } else if (JLI_StrCmp(arg, "-checksource") == 0 ||
1441                    JLI_StrCmp(arg, "-cs") == 0 ||
1442                    JLI_StrCmp(arg, "-noasyncgc") == 0) {
1443             /* No longer supported */
1444             JLI_ReportErrorMessage(ARG_WARN, arg);
1445         } else if (JLI_StrCCmp(arg, "-splash:") == 0) {
1446             ; /* Ignore machine independent options already handled */
1447         } else if (ProcessPlatformOption(arg)) {
1448             ; /* Processing of platform dependent options */
1449         } else {
1450             /* java.class.path set on the command line */
1451             if (JLI_StrCCmp(arg, "-Djava.class.path=") == 0) {
1452                 _have_classpath = JNI_TRUE;
1453             }
1454             AddOption(arg, NULL);
1455         }
1456     }
1457 
1458     if (*pwhat == NULL && --argc >= 0) {
1459         *pwhat = *argv++;
1460     }
1461 
1462     if (*pwhat == NULL) {
1463         /* LM_UNKNOWN okay for options that exit */
1464         if (!listModules && !describeModule && !validateModules) {
1465             *pret = 1;
1466         }
1467     } else if (mode == LM_UNKNOWN) {
1468         /* default to LM_CLASS if -m, -jar and -cp options are
1469          * not specified */
1470         if (!_have_classpath) {
1471             SetClassPath(".");
1472         }
1473         mode = IsSourceFile(arg) ? LM_SOURCE : LM_CLASS;
1474     } else if (mode == LM_CLASS && IsSourceFile(arg)) {
1475         /* override LM_CLASS mode if given a source file */
1476         mode = LM_SOURCE;
1477     }
1478 
1479     if (mode == LM_SOURCE) {
1480         AddOption("--add-modules=ALL-DEFAULT", NULL);
1481         *pwhat = SOURCE_LAUNCHER_MAIN_ENTRY;
1482         // adjust (argc, argv) so that the name of the source file
1483         // is included in the args passed to the source launcher
1484         // main entry class
1485         *pargc = argc + 1;
1486         *pargv = argv - 1;
1487     } else {
1488         if (argc >= 0) {
1489             *pargc = argc;
1490             *pargv = argv;
1491         }
1492     }
1493 
1494     *pmode = mode;
1495 
1496     return JNI_TRUE;
1497 }
1498 
1499 /*
1500  * Initializes the Java Virtual Machine. Also frees options array when
1501  * finished.
1502  */
1503 static jboolean
1504 InitializeJVM(JavaVM **pvm, JNIEnv **penv, InvocationFunctions *ifn)
1505 {
1506     JavaVMInitArgs args;
1507     jint r;
1508 
1509     memset(&args, 0, sizeof(args));
1510     args.version  = JNI_VERSION_1_2;
1511     args.nOptions = numOptions;
1512     args.options  = options;
1513     args.ignoreUnrecognized = JNI_FALSE;
1514 
1515     if (JLI_IsTraceLauncher()) {
1516         int i = 0;
1517         printf("JavaVM args:\n    ");
1518         printf("version 0x%08lx, ", (long)args.version);
1519         printf("ignoreUnrecognized is %s, ",
1520                args.ignoreUnrecognized ? "JNI_TRUE" : "JNI_FALSE");
1521         printf("nOptions is %ld\n", (long)args.nOptions);
1522         for (i = 0; i < numOptions; i++)
1523             printf("    option[%2d] = '%s'\n",
1524                    i, args.options[i].optionString);
1525     }
1526 
1527     r = ifn->CreateJavaVM(pvm, (void **)penv, &args);
1528     JLI_MemFree(options);
1529     return r == JNI_OK;
1530 }
1531 
1532 static jclass helperClass = NULL;
1533 
1534 jclass
1535 GetLauncherHelperClass(JNIEnv *env)
1536 {
1537     if (helperClass == NULL) {
1538         NULL_CHECK0(helperClass = FindBootStrapClass(env,
1539                 "sun/launcher/LauncherHelper"));
1540     }
1541     return helperClass;
1542 }
1543 
1544 static jmethodID makePlatformStringMID = NULL;
1545 /*
1546  * Returns a new Java string object for the specified platform string.
1547  */
1548 static jstring
1549 NewPlatformString(JNIEnv *env, char *s)
1550 {
1551     int len = (int)JLI_StrLen(s);
1552     jbyteArray ary;
1553     jclass cls = GetLauncherHelperClass(env);
1554     NULL_CHECK0(cls);
1555     if (s == NULL)
1556         return 0;
1557 
1558     ary = (*env)->NewByteArray(env, len);
1559     if (ary != 0) {
1560         jstring str = 0;
1561         (*env)->SetByteArrayRegion(env, ary, 0, len, (jbyte *)s);
1562         if (!(*env)->ExceptionOccurred(env)) {
1563             if (makePlatformStringMID == NULL) {
1564                 NULL_CHECK0(makePlatformStringMID = (*env)->GetStaticMethodID(env,
1565                         cls, "makePlatformString", "(Z[B)Ljava/lang/String;"));
1566             }
1567             str = (*env)->CallStaticObjectMethod(env, cls,
1568                     makePlatformStringMID, USE_STDERR, ary);
1569             CHECK_EXCEPTION_RETURN_VALUE(0);
1570             (*env)->DeleteLocalRef(env, ary);
1571             return str;
1572         }
1573     }
1574     return 0;
1575 }
1576 
1577 /*
1578  * Returns a new array of Java string objects for the specified
1579  * array of platform strings.
1580  */
1581 jobjectArray
1582 NewPlatformStringArray(JNIEnv *env, char **strv, int strc)
1583 {
1584     jarray cls;
1585     jarray ary;
1586     int i;
1587 
1588     NULL_CHECK0(cls = FindBootStrapClass(env, "java/lang/String"));
1589     NULL_CHECK0(ary = (*env)->NewObjectArray(env, strc, cls, 0));
1590     CHECK_EXCEPTION_RETURN_VALUE(0);
1591     for (i = 0; i < strc; i++) {
1592         jstring str = NewPlatformString(env, *strv++);
1593         NULL_CHECK0(str);
1594         (*env)->SetObjectArrayElement(env, ary, i, str);
1595         (*env)->DeleteLocalRef(env, str);
1596     }
1597     return ary;
1598 }
1599 
1600 /*
1601  * Loads a class and verifies that the main class is present and it is ok to
1602  * call it for more details refer to the java implementation.
1603  */
1604 static jclass
1605 LoadMainClass(JNIEnv *env, int mode, char *name)
1606 {
1607     jmethodID mid;
1608     jstring str;
1609     jobject result;
1610     jlong start, end;
1611     jclass cls = GetLauncherHelperClass(env);
1612     NULL_CHECK0(cls);
1613     if (JLI_IsTraceLauncher()) {
1614         start = CounterGet();
1615     }
1616     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1617                 "checkAndLoadMain",
1618                 "(ZILjava/lang/String;)Ljava/lang/Class;"));
1619 
1620     NULL_CHECK0(str = NewPlatformString(env, name));
1621     NULL_CHECK0(result = (*env)->CallStaticObjectMethod(env, cls, mid,
1622                                                         USE_STDERR, mode, str));
1623 
1624     if (JLI_IsTraceLauncher()) {
1625         end   = CounterGet();
1626         printf("%ld micro seconds to load main class\n",
1627                (long)(jint)Counter2Micros(end-start));
1628         printf("----%s----\n", JLDEBUG_ENV_ENTRY);
1629     }
1630 
1631     return (jclass)result;
1632 }
1633 
1634 static jclass
1635 GetApplicationClass(JNIEnv *env)
1636 {
1637     jmethodID mid;
1638     jclass appClass;
1639     jclass cls = GetLauncherHelperClass(env);
1640     NULL_CHECK0(cls);
1641     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1642                 "getApplicationClass",
1643                 "()Ljava/lang/Class;"));
1644 
1645     appClass = (*env)->CallStaticObjectMethod(env, cls, mid);
1646     CHECK_EXCEPTION_RETURN_VALUE(0);
1647     return appClass;
1648 }
1649 
1650 static char* expandWildcardOnLongOpt(char* arg) {
1651     char *p, *value;
1652     size_t optLen, valueLen;
1653     p = JLI_StrChr(arg, '=');
1654 
1655     if (p == NULL || p[1] == '\0') {
1656         JLI_ReportErrorMessage(ARG_ERROR1, arg);
1657         exit(1);
1658     }
1659     p++;
1660     value = (char *) JLI_WildcardExpandClasspath(p);
1661     if (p == value) {
1662         // no wildcard
1663         return arg;
1664     }
1665 
1666     optLen = p - arg;
1667     valueLen = JLI_StrLen(value);
1668     p = JLI_MemAlloc(optLen + valueLen + 1);
1669     memcpy(p, arg, optLen);
1670     memcpy(p + optLen, value, valueLen);
1671     p[optLen + valueLen] = '\0';
1672     return p;
1673 }
1674 
1675 /*
1676  * For tools, convert command line args thus:
1677  *   javac -cp foo:foo/"*" -J-ms32m ...
1678  *   java -ms32m -cp JLI_WildcardExpandClasspath(foo:foo/"*") ...
1679  *
1680  * Takes 4 parameters, and returns the populated arguments
1681  */
1682 static void
1683 TranslateApplicationArgs(int jargc, const char **jargv, int *pargc, char ***pargv)
1684 {
1685     int argc = *pargc;
1686     char **argv = *pargv;
1687     int nargc = argc + jargc;
1688     char **nargv = JLI_MemAlloc((nargc + 1) * sizeof(char *));
1689     int i;
1690 
1691     *pargc = nargc;
1692     *pargv = nargv;
1693 
1694     /* Copy the VM arguments (i.e. prefixed with -J) */
1695     for (i = 0; i < jargc; i++) {
1696         const char *arg = jargv[i];
1697         if (arg[0] == '-' && arg[1] == 'J') {
1698             *nargv++ = ((arg + 2) == NULL) ? NULL : JLI_StringDup(arg + 2);
1699         }
1700     }
1701 
1702     for (i = 0; i < argc; i++) {
1703         char *arg = argv[i];
1704         if (arg[0] == '-' && arg[1] == 'J') {
1705             if (arg[2] == '\0') {
1706                 JLI_ReportErrorMessage(ARG_ERROR3);
1707                 exit(1);
1708             }
1709             *nargv++ = arg + 2;
1710         }
1711     }
1712 
1713     /* Copy the rest of the arguments */
1714     for (i = 0; i < jargc ; i++) {
1715         const char *arg = jargv[i];
1716         if (arg[0] != '-' || arg[1] != 'J') {
1717             *nargv++ = (arg == NULL) ? NULL : JLI_StringDup(arg);
1718         }
1719     }
1720     for (i = 0; i < argc; i++) {
1721         char *arg = argv[i];
1722         if (arg[0] == '-') {
1723             if (arg[1] == 'J')
1724                 continue;
1725             if (IsWildCardEnabled()) {
1726                 if (IsClassPathOption(arg) && i < argc - 1) {
1727                     *nargv++ = arg;
1728                     *nargv++ = (char *) JLI_WildcardExpandClasspath(argv[i+1]);
1729                     i++;
1730                     continue;
1731                 }
1732                 if (JLI_StrCCmp(arg, "--class-path=") == 0) {
1733                     *nargv++ = expandWildcardOnLongOpt(arg);
1734                     continue;
1735                 }
1736             }
1737         }
1738         *nargv++ = arg;
1739     }
1740     *nargv = 0;
1741 }
1742 
1743 /*
1744  * For our tools, we try to add 3 VM options:
1745  *      -Denv.class.path=<envcp>
1746  *      -Dapplication.home=<apphome>
1747  *      -Djava.class.path=<appcp>
1748  * <envcp>   is the user's setting of CLASSPATH -- for instance the user
1749  *           tells javac where to find binary classes through this environment
1750  *           variable.  Notice that users will be able to compile against our
1751  *           tools classes (sun.tools.javac.Main) only if they explicitly add
1752  *           tools.jar to CLASSPATH.
1753  * <apphome> is the directory where the application is installed.
1754  * <appcp>   is the classpath to where our apps' classfiles are.
1755  */
1756 static jboolean
1757 AddApplicationOptions(int cpathc, const char **cpathv)
1758 {
1759     char *envcp, *appcp, *apphome;
1760     char home[MAXPATHLEN]; /* application home */
1761     char separator[] = { PATH_SEPARATOR, '\0' };
1762     int size, i;
1763 
1764     {
1765         const char *s = getenv("CLASSPATH");
1766         if (s) {
1767             s = (char *) JLI_WildcardExpandClasspath(s);
1768             /* 40 for -Denv.class.path= */
1769             if (JLI_StrLen(s) + 40 > JLI_StrLen(s)) { // Safeguard from overflow
1770                 envcp = (char *)JLI_MemAlloc(JLI_StrLen(s) + 40);
1771                 sprintf(envcp, "-Denv.class.path=%s", s);
1772                 AddOption(envcp, NULL);
1773             }
1774         }
1775     }
1776 
1777     if (!GetApplicationHome(home, sizeof(home))) {
1778         JLI_ReportErrorMessage(CFG_ERROR5);
1779         return JNI_FALSE;
1780     }
1781 
1782     /* 40 for '-Dapplication.home=' */
1783     apphome = (char *)JLI_MemAlloc(JLI_StrLen(home) + 40);
1784     sprintf(apphome, "-Dapplication.home=%s", home);
1785     AddOption(apphome, NULL);
1786 
1787     /* How big is the application's classpath? */
1788     if (cpathc > 0) {
1789         size = 40;                                 /* 40: "-Djava.class.path=" */
1790         for (i = 0; i < cpathc; i++) {
1791             size += (int)JLI_StrLen(home) + (int)JLI_StrLen(cpathv[i]) + 1; /* 1: separator */
1792         }
1793         appcp = (char *)JLI_MemAlloc(size + 1);
1794         JLI_StrCpy(appcp, "-Djava.class.path=");
1795         for (i = 0; i < cpathc; i++) {
1796             JLI_StrCat(appcp, home);                        /* c:\program files\myapp */
1797             JLI_StrCat(appcp, cpathv[i]);           /* \lib\myapp.jar         */
1798             JLI_StrCat(appcp, separator);           /* ;                      */
1799         }
1800         appcp[JLI_StrLen(appcp)-1] = '\0';  /* remove trailing path separator */
1801         AddOption(appcp, NULL);
1802     }
1803     return JNI_TRUE;
1804 }
1805 
1806 /*
1807  * inject the -Dsun.java.command pseudo property into the args structure
1808  * this pseudo property is used in the HotSpot VM to expose the
1809  * Java class name and arguments to the main method to the VM. The
1810  * HotSpot VM uses this pseudo property to store the Java class name
1811  * (or jar file name) and the arguments to the class's main method
1812  * to the instrumentation memory region. The sun.java.command pseudo
1813  * property is not exported by HotSpot to the Java layer.
1814  */
1815 void
1816 SetJavaCommandLineProp(char *what, int argc, char **argv)
1817 {
1818 
1819     int i = 0;
1820     size_t len = 0;
1821     char* javaCommand = NULL;
1822     char* dashDstr = "-Dsun.java.command=";
1823 
1824     if (what == NULL) {
1825         /* unexpected, one of these should be set. just return without
1826          * setting the property
1827          */
1828         return;
1829     }
1830 
1831     /* determine the amount of memory to allocate assuming
1832      * the individual components will be space separated
1833      */
1834     len = JLI_StrLen(what);
1835     for (i = 0; i < argc; i++) {
1836         len += JLI_StrLen(argv[i]) + 1;
1837     }
1838 
1839     /* allocate the memory */
1840     javaCommand = (char*) JLI_MemAlloc(len + JLI_StrLen(dashDstr) + 1);
1841 
1842     /* build the -D string */
1843     *javaCommand = '\0';
1844     JLI_StrCat(javaCommand, dashDstr);
1845     JLI_StrCat(javaCommand, what);
1846 
1847     for (i = 0; i < argc; i++) {
1848         /* the components of the string are space separated. In
1849          * the case of embedded white space, the relationship of
1850          * the white space separated components to their true
1851          * positional arguments will be ambiguous. This issue may
1852          * be addressed in a future release.
1853          */
1854         JLI_StrCat(javaCommand, " ");
1855         JLI_StrCat(javaCommand, argv[i]);
1856     }
1857 
1858     AddOption(javaCommand, NULL);
1859 }
1860 
1861 /*
1862  * JVM would like to know if it's created by a standard Sun launcher, or by
1863  * user native application, the following property indicates the former.
1864  */
1865 void
1866 SetJavaLauncherProp() {
1867   AddOption("-Dsun.java.launcher=SUN_STANDARD", NULL);
1868 }
1869 
1870 /*
1871  * Prints the version information from the java.version and other properties.
1872  */
1873 static void
1874 PrintJavaVersion(JNIEnv *env, jboolean extraLF)
1875 {
1876     jclass ver;
1877     jmethodID print;
1878 
1879     NULL_CHECK(ver = FindBootStrapClass(env, "java/lang/VersionProps"));
1880     NULL_CHECK(print = (*env)->GetStaticMethodID(env,
1881                                                  ver,
1882                                                  (extraLF == JNI_TRUE) ? "println" : "print",
1883                                                  "(Z)V"
1884                                                  )
1885               );
1886 
1887     (*env)->CallStaticVoidMethod(env, ver, print, printTo);
1888 }
1889 
1890 /*
1891  * Prints all the Java settings, see the java implementation for more details.
1892  */
1893 static void
1894 ShowSettings(JNIEnv *env, char *optString)
1895 {
1896     jmethodID showSettingsID;
1897     jstring joptString;
1898     jclass cls = GetLauncherHelperClass(env);
1899     NULL_CHECK(cls);
1900     NULL_CHECK(showSettingsID = (*env)->GetStaticMethodID(env, cls,
1901             "showSettings", "(ZLjava/lang/String;JJJ)V"));
1902     NULL_CHECK(joptString = (*env)->NewStringUTF(env, optString));
1903     (*env)->CallStaticVoidMethod(env, cls, showSettingsID,
1904                                  USE_STDERR,
1905                                  joptString,
1906                                  (jlong)initialHeapSize,
1907                                  (jlong)maxHeapSize,
1908                                  (jlong)threadStackSize);
1909 }
1910 
1911 /**
1912  * Show resolved modules
1913  */
1914 static void
1915 ShowResolvedModules(JNIEnv *env)
1916 {
1917     jmethodID showResolvedModulesID;
1918     jclass cls = GetLauncherHelperClass(env);
1919     NULL_CHECK(cls);
1920     NULL_CHECK(showResolvedModulesID = (*env)->GetStaticMethodID(env, cls,
1921             "showResolvedModules", "()V"));
1922     (*env)->CallStaticVoidMethod(env, cls, showResolvedModulesID);
1923 }
1924 
1925 /**
1926  * List observable modules
1927  */
1928 static void
1929 ListModules(JNIEnv *env)
1930 {
1931     jmethodID listModulesID;
1932     jclass cls = GetLauncherHelperClass(env);
1933     NULL_CHECK(cls);
1934     NULL_CHECK(listModulesID = (*env)->GetStaticMethodID(env, cls,
1935             "listModules", "()V"));
1936     (*env)->CallStaticVoidMethod(env, cls, listModulesID);
1937 }
1938 
1939 /**
1940  * Describe a module
1941  */
1942 static void
1943 DescribeModule(JNIEnv *env, char *optString)
1944 {
1945     jmethodID describeModuleID;
1946     jstring joptString = NULL;
1947     jclass cls = GetLauncherHelperClass(env);
1948     NULL_CHECK(cls);
1949     NULL_CHECK(describeModuleID = (*env)->GetStaticMethodID(env, cls,
1950             "describeModule", "(Ljava/lang/String;)V"));
1951     NULL_CHECK(joptString = (*env)->NewStringUTF(env, optString));
1952     (*env)->CallStaticVoidMethod(env, cls, describeModuleID, joptString);
1953 }
1954 
1955 /*
1956  * Prints default usage or the Xusage message, see sun.launcher.LauncherHelper.java
1957  */
1958 static void
1959 PrintUsage(JNIEnv* env, jboolean doXUsage)
1960 {
1961   jmethodID initHelp, vmSelect, vmSynonym, printHelp, printXUsageMessage;
1962   jstring jprogname, vm1, vm2;
1963   int i;
1964   jclass cls = GetLauncherHelperClass(env);
1965   NULL_CHECK(cls);
1966   if (doXUsage) {
1967     NULL_CHECK(printXUsageMessage = (*env)->GetStaticMethodID(env, cls,
1968                                         "printXUsageMessage", "(Z)V"));
1969     (*env)->CallStaticVoidMethod(env, cls, printXUsageMessage, printTo);
1970   } else {
1971     NULL_CHECK(initHelp = (*env)->GetStaticMethodID(env, cls,
1972                                         "initHelpMessage", "(Ljava/lang/String;)V"));
1973 
1974     NULL_CHECK(vmSelect = (*env)->GetStaticMethodID(env, cls, "appendVmSelectMessage",
1975                                         "(Ljava/lang/String;Ljava/lang/String;)V"));
1976 
1977     NULL_CHECK(vmSynonym = (*env)->GetStaticMethodID(env, cls,
1978                                         "appendVmSynonymMessage",
1979                                         "(Ljava/lang/String;Ljava/lang/String;)V"));
1980 
1981     NULL_CHECK(printHelp = (*env)->GetStaticMethodID(env, cls,
1982                                         "printHelpMessage", "(Z)V"));
1983 
1984     NULL_CHECK(jprogname = (*env)->NewStringUTF(env, _program_name));
1985 
1986     /* Initialize the usage message with the usual preamble */
1987     (*env)->CallStaticVoidMethod(env, cls, initHelp, jprogname);
1988     CHECK_EXCEPTION_RETURN();
1989 
1990     /* Assemble the other variant part of the usage */
1991     for (i=1; i<knownVMsCount; i++) {
1992       if (knownVMs[i].flag == VM_KNOWN) {
1993         char *longOpt = (char *)JLI_MemAlloc(JLI_StrLen(knownVMs[i].name) + 2);
1994         *longOpt = '\0';
1995         JLI_StrCat(longOpt, "-");
1996         JLI_StrCat(longOpt, knownVMs[i].name);
1997         NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, longOpt));
1998         NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].name+1));
1999         (*env)->CallStaticVoidMethod(env, cls, vmSelect, vm1, vm2);
2000         CHECK_EXCEPTION_RETURN();
2001         JLI_MemFree(longOpt);
2002         /* Mention the short option as a synonym */
2003         NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
2004         NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].name+1));
2005         (*env)->CallStaticVoidMethod(env, cls, vmSynonym, vm1, vm2);
2006         CHECK_EXCEPTION_RETURN();
2007       }
2008     }
2009     for (i=1; i<knownVMsCount; i++) {
2010       if (knownVMs[i].flag == VM_ALIASED_TO) {
2011         NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
2012         NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].alias+1));
2013         (*env)->CallStaticVoidMethod(env, cls, vmSynonym, vm1, vm2);
2014         CHECK_EXCEPTION_RETURN();
2015       }
2016     }
2017 
2018     /* Complete the usage message and print to stderr*/
2019     (*env)->CallStaticVoidMethod(env, cls, printHelp, printTo);
2020   }
2021   return;
2022 }
2023 
2024 /*
2025  * Read the jvm.cfg file and fill the knownJVMs[] array.
2026  *
2027  * The functionality of the jvm.cfg file is subject to change without
2028  * notice and the mechanism will be removed in the future.
2029  *
2030  * The lexical structure of the jvm.cfg file is as follows:
2031  *
2032  *     jvmcfg         :=  { vmLine }
2033  *     vmLine         :=  knownLine
2034  *                    |   aliasLine
2035  *                    |   warnLine
2036  *                    |   ignoreLine
2037  *                    |   errorLine
2038  *                    |   predicateLine
2039  *                    |   commentLine
2040  *     knownLine      :=  flag  "KNOWN"                  EOL
2041  *     warnLine       :=  flag  "WARN"                   EOL
2042  *     ignoreLine     :=  flag  "IGNORE"                 EOL
2043  *     errorLine      :=  flag  "ERROR"                  EOL
2044  *     aliasLine      :=  flag  "ALIASED_TO"       flag  EOL
2045  *     predicateLine  :=  flag  "IF_SERVER_CLASS"  flag  EOL
2046  *     commentLine    :=  "#" text                       EOL
2047  *     flag           :=  "-" identifier
2048  *
2049  * The semantics are that when someone specifies a flag on the command line:
2050  * - if the flag appears on a knownLine, then the identifier is used as
2051  *   the name of the directory holding the JVM library (the name of the JVM).
2052  * - if the flag appears as the first flag on an aliasLine, the identifier
2053  *   of the second flag is used as the name of the JVM.
2054  * - if the flag appears on a warnLine, the identifier is used as the
2055  *   name of the JVM, but a warning is generated.
2056  * - if the flag appears on an ignoreLine, the identifier is recognized as the
2057  *   name of a JVM, but the identifier is ignored and the default vm used
2058  * - if the flag appears on an errorLine, an error is generated.
2059  * - if the flag appears as the first flag on a predicateLine, and
2060  *   the machine on which you are running passes the predicate indicated,
2061  *   then the identifier of the second flag is used as the name of the JVM,
2062  *   otherwise the identifier of the first flag is used as the name of the JVM.
2063  * If no flag is given on the command line, the first vmLine of the jvm.cfg
2064  * file determines the name of the JVM.
2065  * PredicateLines are only interpreted on first vmLine of a jvm.cfg file,
2066  * since they only make sense if someone hasn't specified the name of the
2067  * JVM on the command line.
2068  *
2069  * The intent of the jvm.cfg file is to allow several JVM libraries to
2070  * be installed in different subdirectories of a single JRE installation,
2071  * for space-savings and convenience in testing.
2072  * The intent is explicitly not to provide a full aliasing or predicate
2073  * mechanism.
2074  */
2075 jint
2076 ReadKnownVMs(const char *jvmCfgName, jboolean speculative)
2077 {
2078     FILE *jvmCfg;
2079     char line[MAXPATHLEN+20];
2080     int cnt = 0;
2081     int lineno = 0;
2082     jlong start, end;
2083     int vmType;
2084     char *tmpPtr;
2085     char *altVMName = NULL;
2086     char *serverClassVMName = NULL;
2087     static char *whiteSpace = " \t";
2088     if (JLI_IsTraceLauncher()) {
2089         start = CounterGet();
2090     }
2091 
2092     jvmCfg = fopen(jvmCfgName, "r");
2093     if (jvmCfg == NULL) {
2094       if (!speculative) {
2095         JLI_ReportErrorMessage(CFG_ERROR6, jvmCfgName);
2096         exit(1);
2097       } else {
2098         return -1;
2099       }
2100     }
2101     while (fgets(line, sizeof(line), jvmCfg) != NULL) {
2102         vmType = VM_UNKNOWN;
2103         lineno++;
2104         if (line[0] == '#')
2105             continue;
2106         if (line[0] != '-') {
2107             JLI_ReportErrorMessage(CFG_WARN2, lineno, jvmCfgName);
2108         }
2109         if (cnt >= knownVMsLimit) {
2110             GrowKnownVMs(cnt);
2111         }
2112         line[JLI_StrLen(line)-1] = '\0'; /* remove trailing newline */
2113         tmpPtr = line + JLI_StrCSpn(line, whiteSpace);
2114         if (*tmpPtr == 0) {
2115             JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2116         } else {
2117             /* Null-terminate this string for JLI_StringDup below */
2118             *tmpPtr++ = 0;
2119             tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
2120             if (*tmpPtr == 0) {
2121                 JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2122             } else {
2123                 if (!JLI_StrCCmp(tmpPtr, "KNOWN")) {
2124                     vmType = VM_KNOWN;
2125                 } else if (!JLI_StrCCmp(tmpPtr, "ALIASED_TO")) {
2126                     tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
2127                     if (*tmpPtr != 0) {
2128                         tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
2129                     }
2130                     if (*tmpPtr == 0) {
2131                         JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2132                     } else {
2133                         /* Null terminate altVMName */
2134                         altVMName = tmpPtr;
2135                         tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
2136                         *tmpPtr = 0;
2137                         vmType = VM_ALIASED_TO;
2138                     }
2139                 } else if (!JLI_StrCCmp(tmpPtr, "WARN")) {
2140                     vmType = VM_WARN;
2141                 } else if (!JLI_StrCCmp(tmpPtr, "IGNORE")) {
2142                     vmType = VM_IGNORE;
2143                 } else if (!JLI_StrCCmp(tmpPtr, "ERROR")) {
2144                     vmType = VM_ERROR;
2145                 } else if (!JLI_StrCCmp(tmpPtr, "IF_SERVER_CLASS")) {
2146                     /* ignored */
2147                 } else {
2148                     JLI_ReportErrorMessage(CFG_WARN5, lineno, &jvmCfgName[0]);
2149                     vmType = VM_KNOWN;
2150                 }
2151             }
2152         }
2153 
2154         JLI_TraceLauncher("jvm.cfg[%d] = ->%s<-\n", cnt, line);
2155         if (vmType != VM_UNKNOWN) {
2156             knownVMs[cnt].name = JLI_StringDup(line);
2157             knownVMs[cnt].flag = vmType;
2158             switch (vmType) {
2159             default:
2160                 break;
2161             case VM_ALIASED_TO:
2162                 knownVMs[cnt].alias = JLI_StringDup(altVMName);
2163                 JLI_TraceLauncher("    name: %s  vmType: %s  alias: %s\n",
2164                    knownVMs[cnt].name, "VM_ALIASED_TO", knownVMs[cnt].alias);
2165                 break;
2166             }
2167             cnt++;
2168         }
2169     }
2170     fclose(jvmCfg);
2171     knownVMsCount = cnt;
2172 
2173     if (JLI_IsTraceLauncher()) {
2174         end   = CounterGet();
2175         printf("%ld micro seconds to parse jvm.cfg\n",
2176                (long)(jint)Counter2Micros(end-start));
2177     }
2178 
2179     return cnt;
2180 }
2181 
2182 
2183 static void
2184 GrowKnownVMs(int minimum)
2185 {
2186     struct vmdesc* newKnownVMs;
2187     int newMax;
2188 
2189     newMax = (knownVMsLimit == 0 ? INIT_MAX_KNOWN_VMS : (2 * knownVMsLimit));
2190     if (newMax <= minimum) {
2191         newMax = minimum;
2192     }
2193     newKnownVMs = (struct vmdesc*) JLI_MemAlloc(newMax * sizeof(struct vmdesc));
2194     if (knownVMs != NULL) {
2195         memcpy(newKnownVMs, knownVMs, knownVMsLimit * sizeof(struct vmdesc));
2196     }
2197     JLI_MemFree(knownVMs);
2198     knownVMs = newKnownVMs;
2199     knownVMsLimit = newMax;
2200 }
2201 
2202 
2203 /* Returns index of VM or -1 if not found */
2204 static int
2205 KnownVMIndex(const char* name)
2206 {
2207     int i;
2208     if (JLI_StrCCmp(name, "-J") == 0) name += 2;
2209     if (JLI_StrCCmp(name, "--") == 0) name += 1;
2210     for (i = 0; i < knownVMsCount; i++) {
2211         if (!JLI_StrCmp(name, knownVMs[i].name)) {
2212             return i;
2213         }
2214     }
2215     return -1;
2216 }
2217 
2218 static void
2219 FreeKnownVMs()
2220 {
2221     int i;
2222     for (i = 0; i < knownVMsCount; i++) {
2223         JLI_MemFree(knownVMs[i].name);
2224         knownVMs[i].name = NULL;
2225     }
2226     JLI_MemFree(knownVMs);
2227 }
2228 
2229 /*
2230  * Displays the splash screen according to the jar file name
2231  * and image file names stored in environment variables
2232  */
2233 void
2234 ShowSplashScreen()
2235 {
2236     const char *jar_name = getenv(SPLASH_JAR_ENV_ENTRY);
2237     const char *file_name = getenv(SPLASH_FILE_ENV_ENTRY);
2238     int data_size;
2239     void *image_data = NULL;
2240     float scale_factor = 1;
2241     char *scaled_splash_name = NULL;
2242     jboolean isImageScaled = JNI_FALSE;
2243     size_t maxScaledImgNameLength = 0;
2244     if (file_name == NULL){
2245         return;
2246     }
2247     maxScaledImgNameLength = DoSplashGetScaledImgNameMaxPstfixLen(file_name);
2248 
2249     scaled_splash_name = JLI_MemAlloc(
2250                             maxScaledImgNameLength * sizeof(char));
2251     isImageScaled = DoSplashGetScaledImageName(jar_name, file_name,
2252                             &scale_factor,
2253                             scaled_splash_name, maxScaledImgNameLength);
2254     if (jar_name) {
2255 
2256         if (isImageScaled) {
2257             image_data = JLI_JarUnpackFile(
2258                     jar_name, scaled_splash_name, &data_size);
2259         }
2260 
2261         if (!image_data) {
2262             scale_factor = 1;
2263             image_data = JLI_JarUnpackFile(
2264                             jar_name, file_name, &data_size);
2265         }
2266         if (image_data) {
2267             DoSplashInit();
2268             DoSplashSetScaleFactor(scale_factor);
2269             DoSplashLoadMemory(image_data, data_size);
2270             JLI_MemFree(image_data);
2271         }
2272     } else {
2273         DoSplashInit();
2274         if (isImageScaled) {
2275             DoSplashSetScaleFactor(scale_factor);
2276             DoSplashLoadFile(scaled_splash_name);
2277         } else {
2278             DoSplashLoadFile(file_name);
2279         }
2280     }
2281     JLI_MemFree(scaled_splash_name);
2282 
2283     DoSplashSetFileJarName(file_name, jar_name);
2284 
2285     /*
2286      * Done with all command line processing and potential re-execs so
2287      * clean up the environment.
2288      */
2289     (void)UnsetEnv(ENV_ENTRY);
2290     (void)UnsetEnv(SPLASH_FILE_ENV_ENTRY);
2291     (void)UnsetEnv(SPLASH_JAR_ENV_ENTRY);
2292 
2293     JLI_MemFree(splash_jar_entry);
2294     JLI_MemFree(splash_file_entry);
2295 
2296 }
2297 
2298 const char*
2299 GetFullVersion()
2300 {
2301     return _fVersion;
2302 }
2303 
2304 const char*
2305 GetProgramName()
2306 {
2307     return _program_name;
2308 }
2309 
2310 const char*
2311 GetLauncherName()
2312 {
2313     return _launcher_name;
2314 }
2315 
2316 jboolean
2317 IsJavaArgs()
2318 {
2319     return _is_java_args;
2320 }
2321 
2322 static jboolean
2323 IsWildCardEnabled()
2324 {
2325     return _wc_enabled;
2326 }
2327 
2328 int
2329 ContinueInNewThread(InvocationFunctions* ifn, jlong threadStackSize,
2330                     int argc, char **argv,
2331                     int mode, char *what, int ret)
2332 {
2333 
2334     /*
2335      * If user doesn't specify stack size, check if VM has a preference.
2336      * Note that HotSpot no longer supports JNI_VERSION_1_1 but it will
2337      * return its default stack size through the init args structure.
2338      */
2339     if (threadStackSize == 0) {
2340       struct JDK1_1InitArgs args1_1;
2341       memset((void*)&args1_1, 0, sizeof(args1_1));
2342       args1_1.version = JNI_VERSION_1_1;
2343       ifn->GetDefaultJavaVMInitArgs(&args1_1);  /* ignore return value */
2344       if (args1_1.javaStackSize > 0) {
2345          threadStackSize = args1_1.javaStackSize;
2346       }
2347     }
2348 
2349     { /* Create a new thread to create JVM and invoke main method */
2350       JavaMainArgs args;
2351       int rslt;
2352 
2353       args.argc = argc;
2354       args.argv = argv;
2355       args.mode = mode;
2356       args.what = what;
2357       args.ifn = *ifn;
2358 
2359       rslt = ContinueInNewThread0(JavaMain, threadStackSize, (void*)&args);
2360       /* If the caller has deemed there is an error we
2361        * simply return that, otherwise we return the value of
2362        * the callee
2363        */
2364       return (ret != 0) ? ret : rslt;
2365     }
2366 }
2367 
2368 static void
2369 DumpState()
2370 {
2371     if (!JLI_IsTraceLauncher()) return ;
2372     printf("Launcher state:\n");
2373     printf("\tFirst application arg index: %d\n", JLI_GetAppArgIndex());
2374     printf("\tdebug:%s\n", (JLI_IsTraceLauncher() == JNI_TRUE) ? "on" : "off");
2375     printf("\tjavargs:%s\n", (_is_java_args == JNI_TRUE) ? "on" : "off");
2376     printf("\tprogram name:%s\n", GetProgramName());
2377     printf("\tlauncher name:%s\n", GetLauncherName());
2378     printf("\tjavaw:%s\n", (IsJavaw() == JNI_TRUE) ? "on" : "off");
2379     printf("\tfullversion:%s\n", GetFullVersion());
2380 }
2381 
2382 /*
2383  * A utility procedure to always print to stderr
2384  */
2385 JNIEXPORT void JNICALL
2386 JLI_ReportMessage(const char* fmt, ...)
2387 {
2388     va_list vl;
2389     va_start(vl, fmt);
2390     vfprintf(stderr, fmt, vl);
2391     fprintf(stderr, "\n");
2392     va_end(vl);
2393 }
2394 
2395 /*
2396  * A utility procedure to always print to stdout
2397  */
2398 void
2399 JLI_ShowMessage(const char* fmt, ...)
2400 {
2401     va_list vl;
2402     va_start(vl, fmt);
2403     vfprintf(stdout, fmt, vl);
2404     fprintf(stdout, "\n");
2405     va_end(vl);
2406 }