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