java.c revision 16598:397d1eb78030
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 != '-' || isTerminalOpt(arg)) {
773                return;
774            }
775        }
776        /*
777         * The following case checks for "-XX:NativeMemoryTracking=value".
778         * If value is non null, an environmental variable set to this value
779         * will be created to be used by the JVM.
780         * The argument is passed to the JVM, which will check validity.
781         * The JVM is responsible for removing the env variable.
782         */
783        if (JLI_StrCCmp(arg, "-XX:NativeMemoryTracking=") == 0) {
784            int retval;
785            // get what follows this parameter, include "="
786            size_t pnlen = JLI_StrLen("-XX:NativeMemoryTracking=");
787            if (JLI_StrLen(arg) > pnlen) {
788                char* value = arg + pnlen;
789                size_t pbuflen = pnlen + JLI_StrLen(value) + 10; // 10 max pid digits
790
791                /*
792                 * ensures that malloc successful
793                 * DONT JLI_MemFree() pbuf.  JLI_PutEnv() uses system call
794                 *   that could store the address.
795                 */
796                char * pbuf = (char*)JLI_MemAlloc(pbuflen);
797
798                JLI_Snprintf(pbuf, pbuflen, "%s%d=%s", NMT_Env_Name, JLI_GetPid(), value);
799                retval = JLI_PutEnv(pbuf);
800                if (JLI_IsTraceLauncher()) {
801                    char* envName;
802                    char* envBuf;
803
804                    // ensures that malloc successful
805                    envName = (char*)JLI_MemAlloc(pbuflen);
806                    JLI_Snprintf(envName, pbuflen, "%s%d", NMT_Env_Name, JLI_GetPid());
807
808                    printf("TRACER_MARKER: NativeMemoryTracking: env var is %s\n",envName);
809                    printf("TRACER_MARKER: NativeMemoryTracking: putenv arg %s\n",pbuf);
810                    envBuf = getenv(envName);
811                    printf("TRACER_MARKER: NativeMemoryTracking: got value %s\n",envBuf);
812                    free(envName);
813                }
814
815            }
816
817        }
818
819    }
820}
821
822/* copied from HotSpot function "atomll()" */
823static int
824parse_size(const char *s, jlong *result) {
825  jlong n = 0;
826  int args_read = sscanf(s, JLONG_FORMAT_SPECIFIER, &n);
827  if (args_read != 1) {
828    return 0;
829  }
830  while (*s != '\0' && *s >= '0' && *s <= '9') {
831    s++;
832  }
833  // 4705540: illegal if more characters are found after the first non-digit
834  if (JLI_StrLen(s) > 1) {
835    return 0;
836  }
837  switch (*s) {
838    case 'T': case 't':
839      *result = n * GB * KB;
840      return 1;
841    case 'G': case 'g':
842      *result = n * GB;
843      return 1;
844    case 'M': case 'm':
845      *result = n * MB;
846      return 1;
847    case 'K': case 'k':
848      *result = n * KB;
849      return 1;
850    case '\0':
851      *result = n;
852      return 1;
853    default:
854      /* Create JVM with default stack and let VM handle malformed -Xss string*/
855      return 0;
856  }
857}
858
859/*
860 * Adds a new VM option with the given name and value.
861 */
862void
863AddOption(char *str, void *info)
864{
865    /*
866     * Expand options array if needed to accommodate at least one more
867     * VM option.
868     */
869    if (numOptions >= maxOptions) {
870        if (options == 0) {
871            maxOptions = 4;
872            options = JLI_MemAlloc(maxOptions * sizeof(JavaVMOption));
873        } else {
874            JavaVMOption *tmp;
875            maxOptions *= 2;
876            tmp = JLI_MemAlloc(maxOptions * sizeof(JavaVMOption));
877            memcpy(tmp, options, numOptions * sizeof(JavaVMOption));
878            JLI_MemFree(options);
879            options = tmp;
880        }
881    }
882    options[numOptions].optionString = str;
883    options[numOptions++].extraInfo = info;
884
885    if (JLI_StrCCmp(str, "-Xss") == 0) {
886        jlong tmp;
887        if (parse_size(str + 4, &tmp)) {
888            threadStackSize = tmp;
889            /*
890             * Make sure the thread stack size is big enough that we won't get a stack
891             * overflow before the JVM startup code can check to make sure the stack
892             * is big enough.
893             */
894            if (threadStackSize < (jlong)STACK_SIZE_MINIMUM) {
895                threadStackSize = STACK_SIZE_MINIMUM;
896            }
897        }
898    }
899
900    if (JLI_StrCCmp(str, "-Xmx") == 0) {
901        jlong tmp;
902        if (parse_size(str + 4, &tmp)) {
903            maxHeapSize = tmp;
904        }
905    }
906
907    if (JLI_StrCCmp(str, "-Xms") == 0) {
908        jlong tmp;
909        if (parse_size(str + 4, &tmp)) {
910           initialHeapSize = tmp;
911        }
912    }
913}
914
915static void
916SetClassPath(const char *s)
917{
918    char *def;
919    const char *orig = s;
920    static const char format[] = "-Djava.class.path=%s";
921    /*
922     * usually we should not get a null pointer, but there are cases where
923     * we might just get one, in which case we simply ignore it, and let the
924     * caller deal with it
925     */
926    if (s == NULL)
927        return;
928    s = JLI_WildcardExpandClasspath(s);
929    if (sizeof(format) - 2 + JLI_StrLen(s) < JLI_StrLen(s))
930        // s is became corrupted after expanding wildcards
931        return;
932    def = JLI_MemAlloc(sizeof(format)
933                       - 2 /* strlen("%s") */
934                       + JLI_StrLen(s));
935    sprintf(def, format, s);
936    AddOption(def, NULL);
937    if (s != orig)
938        JLI_MemFree((char *) s);
939    _have_classpath = JNI_TRUE;
940}
941
942static void
943AddLongFormOption(const char *option, const char *arg)
944{
945    static const char format[] = "%s=%s";
946    char *def;
947    size_t def_len;
948
949    def_len = JLI_StrLen(option) + 1 + JLI_StrLen(arg) + 1;
950    def = JLI_MemAlloc(def_len);
951    JLI_Snprintf(def, def_len, format, option, arg);
952    AddOption(def, NULL);
953}
954
955static void
956SetMainModule(const char *s)
957{
958    static const char format[] = "-Djdk.module.main=%s";
959    char* slash = JLI_StrChr(s, '/');
960    size_t s_len, def_len;
961    char *def;
962
963    /* value may be <module> or <module>/<mainclass> */
964    if (slash == NULL) {
965        s_len = JLI_StrLen(s);
966    } else {
967        s_len = (size_t) (slash - s);
968    }
969    def_len = sizeof(format)
970               - 2 /* strlen("%s") */
971               + s_len;
972    def = JLI_MemAlloc(def_len);
973    JLI_Snprintf(def, def_len, format, s);
974    AddOption(def, NULL);
975}
976
977/*
978 * The SelectVersion() routine ensures that an appropriate version of
979 * the JRE is running.  The specification for the appropriate version
980 * is obtained from either the manifest of a jar file (preferred) or
981 * from command line options.
982 * The routine also parses splash screen command line options and
983 * passes on their values in private environment variables.
984 */
985static void
986SelectVersion(int argc, char **argv, char **main_class)
987{
988    char    *arg;
989    char    *operand;
990    char    *version = NULL;
991    char    *jre = NULL;
992    int     jarflag = 0;
993    int     headlessflag = 0;
994    int     restrict_search = -1;               /* -1 implies not known */
995    manifest_info info;
996    char    env_entry[MAXNAMELEN + 24] = ENV_ENTRY "=";
997    char    *splash_file_name = NULL;
998    char    *splash_jar_name = NULL;
999    char    *env_in;
1000    int     res;
1001    jboolean has_arg;
1002
1003    /*
1004     * If the version has already been selected, set *main_class
1005     * with the value passed through the environment (if any) and
1006     * simply return.
1007     */
1008
1009    /*
1010     * This environmental variable can be set by mJRE capable JREs
1011     * [ 1.5 thru 1.8 ].  All other aspects of mJRE processing have been
1012     * stripped by those JREs.  This environmental variable allows 1.9+
1013     * JREs to be started by these mJRE capable JREs.
1014     * Note that mJRE directives in the jar manifest file would have been
1015     * ignored for a JRE started by another JRE...
1016     * .. skipped for JRE 1.5 and beyond.
1017     * .. not even checked for pre 1.5.
1018     */
1019    if ((env_in = getenv(ENV_ENTRY)) != NULL) {
1020        if (*env_in != '\0')
1021            *main_class = JLI_StringDup(env_in);
1022        return;
1023    }
1024
1025    /*
1026     * Scan through the arguments for options relevant to multiple JRE
1027     * support.  Multiple JRE support existed in JRE versions 1.5 thru 1.8.
1028     *
1029     * This capability is no longer available with JRE versions 1.9 and later.
1030     * These command line options are reported as errors.
1031     */
1032
1033    argc--;
1034    argv++;
1035    while ((arg = *argv) != 0 && *arg == '-') {
1036        has_arg = IsOptionWithArgument(argc, argv);
1037        if (JLI_StrCCmp(arg, "-version:") == 0) {
1038            JLI_ReportErrorMessage(SPC_ERROR1);
1039        } else if (JLI_StrCmp(arg, "-jre-restrict-search") == 0) {
1040            JLI_ReportErrorMessage(SPC_ERROR2);
1041        } else if (JLI_StrCmp(arg, "-jre-no-restrict-search") == 0) {
1042            JLI_ReportErrorMessage(SPC_ERROR2);
1043        } else {
1044            if (JLI_StrCmp(arg, "-jar") == 0)
1045                jarflag = 1;
1046            if (IsWhiteSpaceOption(arg)) {
1047                if (has_arg) {
1048                    argc--;
1049                    argv++;
1050                    arg = *argv;
1051                }
1052            }
1053
1054            /*
1055             * Checking for headless toolkit option in the some way as AWT does:
1056             * "true" means true and any other value means false
1057             */
1058            if (JLI_StrCmp(arg, "-Djava.awt.headless=true") == 0) {
1059                headlessflag = 1;
1060            } else if (JLI_StrCCmp(arg, "-Djava.awt.headless=") == 0) {
1061                headlessflag = 0;
1062            } else if (JLI_StrCCmp(arg, "-splash:") == 0) {
1063                splash_file_name = arg+8;
1064            }
1065        }
1066        argc--;
1067        argv++;
1068    }
1069    if (argc <= 0) {    /* No operand? Possibly legit with -[full]version */
1070        operand = NULL;
1071    } else {
1072        argc--;
1073        operand = *argv++;
1074    }
1075
1076    /*
1077     * If there is a jar file, read the manifest. If the jarfile can't be
1078     * read, the manifest can't be read from the jar file, or the manifest
1079     * is corrupt, issue the appropriate error messages and exit.
1080     *
1081     * Even if there isn't a jar file, construct a manifest_info structure
1082     * containing the command line information.  It's a convenient way to carry
1083     * this data around.
1084     */
1085    if (jarflag && operand) {
1086        if ((res = JLI_ParseManifest(operand, &info)) != 0) {
1087            if (res == -1)
1088                JLI_ReportErrorMessage(JAR_ERROR2, operand);
1089            else
1090                JLI_ReportErrorMessage(JAR_ERROR3, operand);
1091            exit(1);
1092        }
1093
1094        /*
1095         * Command line splash screen option should have precedence
1096         * over the manifest, so the manifest data is used only if
1097         * splash_file_name has not been initialized above during command
1098         * line parsing
1099         */
1100        if (!headlessflag && !splash_file_name && info.splashscreen_image_file_name) {
1101            splash_file_name = info.splashscreen_image_file_name;
1102            splash_jar_name = operand;
1103        }
1104    } else {
1105        info.manifest_version = NULL;
1106        info.main_class = NULL;
1107        info.jre_version = NULL;
1108        info.jre_restrict_search = 0;
1109    }
1110
1111    /*
1112     * Passing on splash screen info in environment variables
1113     */
1114    if (splash_file_name && !headlessflag) {
1115        char* splash_file_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_FILE_ENV_ENTRY "=")+JLI_StrLen(splash_file_name)+1);
1116        JLI_StrCpy(splash_file_entry, SPLASH_FILE_ENV_ENTRY "=");
1117        JLI_StrCat(splash_file_entry, splash_file_name);
1118        putenv(splash_file_entry);
1119    }
1120    if (splash_jar_name && !headlessflag) {
1121        char* splash_jar_entry = JLI_MemAlloc(JLI_StrLen(SPLASH_JAR_ENV_ENTRY "=")+JLI_StrLen(splash_jar_name)+1);
1122        JLI_StrCpy(splash_jar_entry, SPLASH_JAR_ENV_ENTRY "=");
1123        JLI_StrCat(splash_jar_entry, splash_jar_name);
1124        putenv(splash_jar_entry);
1125    }
1126
1127
1128    /*
1129     * "Valid" returns (other than unrecoverable errors) follow.  Set
1130     * main_class as a side-effect of this routine.
1131     */
1132    if (info.main_class != NULL)
1133        *main_class = JLI_StringDup(info.main_class);
1134
1135    if (info.jre_version == NULL) {
1136        JLI_FreeManifest();
1137        return;
1138    }
1139
1140}
1141
1142/*
1143 * Test if the current argv is an option, i.e. with a leading `-`
1144 * and followed with an argument without a leading `-`.
1145 */
1146static jboolean
1147IsOptionWithArgument(int argc, char** argv) {
1148    char* option;
1149    char* arg;
1150
1151    if (argc <= 1)
1152        return JNI_FALSE;
1153
1154    option = *argv;
1155    arg = *(argv+1);
1156    return *option == '-' && *arg != '-';
1157}
1158
1159/*
1160 * Gets the option, and its argument if the option has an argument.
1161 * It will update *pargc, **pargv to the next option.
1162 */
1163static int
1164GetOpt(int *pargc, char ***pargv, char **poption, char **pvalue) {
1165    int argc = *pargc;
1166    char** argv = *pargv;
1167    char* arg = *argv;
1168
1169    char* option = arg;
1170    char* value = NULL;
1171    char* equals = NULL;
1172    int kind = LAUNCHER_OPTION;
1173    jboolean has_arg = JNI_FALSE;
1174
1175    // check if this option may be a white-space option with an argument
1176    has_arg = IsOptionWithArgument(argc, argv);
1177
1178    argv++; --argc;
1179    if (IsLauncherOption(arg)) {
1180        if (has_arg) {
1181            value = *argv;
1182            argv++; --argc;
1183        }
1184        kind = IsLauncherMainOption(arg) ? LAUNCHER_MAIN_OPTION
1185                                         : LAUNCHER_OPTION_WITH_ARGUMENT;
1186    } else if (IsModuleOption(arg)) {
1187        kind = VM_LONG_OPTION_WITH_ARGUMENT;
1188        if (has_arg) {
1189            value = *argv;
1190            argv++; --argc;
1191        }
1192
1193        /*
1194         * Support short form alias
1195         */
1196        if (JLI_StrCmp(arg, "-p") == 0) {
1197            option = "--module-path";
1198        }
1199
1200    } else if (JLI_StrCCmp(arg, "--") == 0 && (equals = JLI_StrChr(arg, '=')) != NULL) {
1201        value = equals+1;
1202        if (JLI_StrCCmp(arg, "--list-modules=") == 0 ||
1203            JLI_StrCCmp(arg, "--module=") == 0 ||
1204            JLI_StrCCmp(arg, "--class-path=") == 0) {
1205            kind = LAUNCHER_OPTION_WITH_ARGUMENT;
1206        } else {
1207            kind = VM_LONG_OPTION;
1208        }
1209    }
1210
1211    *pargc = argc;
1212    *pargv = argv;
1213    *poption = option;
1214    *pvalue = value;
1215    return kind;
1216}
1217
1218/*
1219 * Parses command line arguments.  Returns JNI_FALSE if launcher
1220 * should exit without starting vm, returns JNI_TRUE if vm needs
1221 * to be started to process given options.  *pret (the launcher
1222 * process return value) is set to 0 for a normal exit.
1223 */
1224static jboolean
1225ParseArguments(int *pargc, char ***pargv,
1226               int *pmode, char **pwhat,
1227               int *pret, const char *jrepath)
1228{
1229    int argc = *pargc;
1230    char **argv = *pargv;
1231    int mode = LM_UNKNOWN;
1232    char *arg;
1233
1234    *pret = 0;
1235
1236    while ((arg = *argv) != 0 && *arg == '-') {
1237        char *option = NULL;
1238        char *value = NULL;
1239        int kind = GetOpt(&argc, &argv, &option, &value);
1240        jboolean has_arg = value != NULL && JLI_StrLen(value) > 0;
1241        jboolean has_arg_any_len = value != NULL;
1242
1243/*
1244 * Option to set main entry point
1245 */
1246        if (JLI_StrCmp(arg, "-jar") == 0) {
1247            ARG_CHECK(argc, ARG_ERROR2, arg);
1248            mode = LM_JAR;
1249        } else if (JLI_StrCmp(arg, "--module") == 0 ||
1250                   JLI_StrCCmp(arg, "--module=") == 0 ||
1251                   JLI_StrCmp(arg, "-m") == 0) {
1252            REPORT_ERROR (has_arg, ARG_ERROR5, arg);
1253            SetMainModule(value);
1254            mode = LM_MODULE;
1255            if (has_arg) {
1256               *pwhat = value;
1257                break;
1258            }
1259        } else if (JLI_StrCmp(arg, "--class-path") == 0 ||
1260                   JLI_StrCCmp(arg, "--class-path=") == 0 ||
1261                   JLI_StrCmp(arg, "-classpath") == 0 ||
1262                   JLI_StrCmp(arg, "-cp") == 0) {
1263            REPORT_ERROR (has_arg_any_len, ARG_ERROR1, arg);
1264            SetClassPath(value);
1265            mode = LM_CLASS;
1266        } else if (JLI_StrCmp(arg, "--list-modules") == 0 ||
1267                   JLI_StrCCmp(arg, "--list-modules=") == 0) {
1268            listModules = arg;
1269
1270            // set listModules to --list-modules=<module-names> if argument is specified
1271            if (JLI_StrCmp(arg, "--list-modules") == 0 && has_arg) {
1272                static const char format[] = "%s=%s";
1273                size_t buflen = JLI_StrLen(option) + 2 + JLI_StrLen(value);
1274                listModules = JLI_MemAlloc(buflen);
1275                JLI_Snprintf(listModules, buflen, format, option, value);
1276            }
1277            return JNI_TRUE;
1278/*
1279 * Parse white-space options
1280 */
1281        } else if (has_arg) {
1282            if (kind == VM_LONG_OPTION) {
1283                AddOption(option, NULL);
1284            } else if (kind == VM_LONG_OPTION_WITH_ARGUMENT) {
1285                AddLongFormOption(option, value);
1286            }
1287/*
1288 * Error missing argument
1289 */
1290        } else if (!has_arg && (JLI_StrCmp(arg, "--module-path") == 0 ||
1291                                JLI_StrCmp(arg, "-p") == 0 ||
1292                                JLI_StrCmp(arg, "--upgrade-module-path") == 0)) {
1293            REPORT_ERROR (has_arg, ARG_ERROR4, arg);
1294
1295        } else if (!has_arg && (IsModuleOption(arg) || IsLongFormModuleOption(arg))) {
1296            REPORT_ERROR (has_arg, ARG_ERROR6, arg);
1297/*
1298 * The following cases will cause the argument parsing to stop
1299 */
1300        } else if (JLI_StrCmp(arg, "-help") == 0 ||
1301                   JLI_StrCmp(arg, "-h") == 0 ||
1302                   JLI_StrCmp(arg, "-?") == 0) {
1303            printUsage = JNI_TRUE;
1304            return JNI_TRUE;
1305        } else if (JLI_StrCmp(arg, "--help") == 0) {
1306            printUsage = JNI_TRUE;
1307            printTo = USE_STDOUT;
1308            return JNI_TRUE;
1309        } else if (JLI_StrCmp(arg, "-version") == 0) {
1310            printVersion = JNI_TRUE;
1311            return JNI_TRUE;
1312        } else if (JLI_StrCmp(arg, "--version") == 0) {
1313            printVersion = JNI_TRUE;
1314            printTo = USE_STDOUT;
1315            return JNI_TRUE;
1316        } else if (JLI_StrCmp(arg, "-showversion") == 0) {
1317            showVersion = JNI_TRUE;
1318        } else if (JLI_StrCmp(arg, "--show-version") == 0) {
1319            showVersion = JNI_TRUE;
1320            printTo = USE_STDOUT;
1321        } else if (JLI_StrCmp(arg, "--dry-run") == 0) {
1322            dryRun = JNI_TRUE;
1323        } else if (JLI_StrCmp(arg, "-X") == 0) {
1324            printXUsage = JNI_TRUE;
1325            return JNI_TRUE;
1326        } else if (JLI_StrCmp(arg, "--help-extra") == 0) {
1327            printXUsage = JNI_TRUE;
1328            printTo = USE_STDOUT;
1329            return JNI_TRUE;
1330/*
1331 * The following case checks for -XshowSettings OR -XshowSetting:SUBOPT.
1332 * In the latter case, any SUBOPT value not recognized will default to "all"
1333 */
1334        } else if (JLI_StrCmp(arg, "-XshowSettings") == 0 ||
1335                   JLI_StrCCmp(arg, "-XshowSettings:") == 0) {
1336            showSettings = arg;
1337        } else if (JLI_StrCmp(arg, "-Xdiag") == 0) {
1338            AddOption("-Dsun.java.launcher.diag=true", NULL);
1339            AddOption("-Djdk.launcher.traceResolver=true", NULL);
1340        } else if (JLI_StrCmp(arg, "-Xdiag:resolver") == 0) {
1341            AddOption("-Djdk.launcher.traceResolver=true", NULL);
1342/*
1343 * The following case provide backward compatibility with old-style
1344 * command line options.
1345 */
1346        } else if (JLI_StrCmp(arg, "-fullversion") == 0) {
1347            JLI_ReportMessage("%s full version \"%s\"", _launcher_name, GetFullVersion());
1348            return JNI_FALSE;
1349        } else if (JLI_StrCmp(arg, "--full-version") == 0) {
1350            JLI_ShowMessage("%s %s", _launcher_name, GetFullVersion());
1351            return JNI_FALSE;
1352        } else if (JLI_StrCmp(arg, "-verbosegc") == 0) {
1353            AddOption("-verbose:gc", NULL);
1354        } else if (JLI_StrCmp(arg, "-t") == 0) {
1355            AddOption("-Xt", NULL);
1356        } else if (JLI_StrCmp(arg, "-tm") == 0) {
1357            AddOption("-Xtm", NULL);
1358        } else if (JLI_StrCmp(arg, "-debug") == 0) {
1359            AddOption("-Xdebug", NULL);
1360        } else if (JLI_StrCmp(arg, "-noclassgc") == 0) {
1361            AddOption("-Xnoclassgc", NULL);
1362        } else if (JLI_StrCmp(arg, "-Xfuture") == 0) {
1363            AddOption("-Xverify:all", NULL);
1364        } else if (JLI_StrCmp(arg, "-verify") == 0) {
1365            AddOption("-Xverify:all", NULL);
1366        } else if (JLI_StrCmp(arg, "-verifyremote") == 0) {
1367            AddOption("-Xverify:remote", NULL);
1368        } else if (JLI_StrCmp(arg, "-noverify") == 0) {
1369            AddOption("-Xverify:none", NULL);
1370        } else if (JLI_StrCCmp(arg, "-ss") == 0 ||
1371                   JLI_StrCCmp(arg, "-oss") == 0 ||
1372                   JLI_StrCCmp(arg, "-ms") == 0 ||
1373                   JLI_StrCCmp(arg, "-mx") == 0) {
1374            char *tmp = JLI_MemAlloc(JLI_StrLen(arg) + 6);
1375            sprintf(tmp, "-X%s", arg + 1); /* skip '-' */
1376            AddOption(tmp, NULL);
1377        } else if (JLI_StrCmp(arg, "-checksource") == 0 ||
1378                   JLI_StrCmp(arg, "-cs") == 0 ||
1379                   JLI_StrCmp(arg, "-noasyncgc") == 0) {
1380            /* No longer supported */
1381            JLI_ReportErrorMessage(ARG_WARN, arg);
1382        } else if (JLI_StrCCmp(arg, "-splash:") == 0) {
1383            ; /* Ignore machine independent options already handled */
1384        } else if (ProcessPlatformOption(arg)) {
1385            ; /* Processing of platform dependent options */
1386        } else if (RemovableOption(arg)) {
1387            ; /* Do not pass option to vm. */
1388        } else {
1389            /* java.class.path set on the command line */
1390            if (JLI_StrCCmp(arg, "-Djava.class.path=") == 0) {
1391                _have_classpath = JNI_TRUE;
1392            }
1393            AddOption(arg, NULL);
1394        }
1395    }
1396
1397    if (*pwhat == NULL && --argc >= 0) {
1398        *pwhat = *argv++;
1399    }
1400
1401    if (*pwhat == NULL) {
1402        *pret = 1;
1403    } else if (mode == LM_UNKNOWN) {
1404        /* default to LM_CLASS if -m, -jar and -cp options are
1405         * not specified */
1406        if (!_have_classpath) {
1407            SetClassPath(".");
1408        }
1409        mode = LM_CLASS;
1410    }
1411
1412    if (argc >= 0) {
1413        *pargc = argc;
1414        *pargv = argv;
1415    }
1416
1417    *pmode = mode;
1418
1419    return JNI_TRUE;
1420}
1421
1422/*
1423 * Initializes the Java Virtual Machine. Also frees options array when
1424 * finished.
1425 */
1426static jboolean
1427InitializeJVM(JavaVM **pvm, JNIEnv **penv, InvocationFunctions *ifn)
1428{
1429    JavaVMInitArgs args;
1430    jint r;
1431
1432    memset(&args, 0, sizeof(args));
1433    args.version  = JNI_VERSION_1_2;
1434    args.nOptions = numOptions;
1435    args.options  = options;
1436    args.ignoreUnrecognized = JNI_FALSE;
1437
1438    if (JLI_IsTraceLauncher()) {
1439        int i = 0;
1440        printf("JavaVM args:\n    ");
1441        printf("version 0x%08lx, ", (long)args.version);
1442        printf("ignoreUnrecognized is %s, ",
1443               args.ignoreUnrecognized ? "JNI_TRUE" : "JNI_FALSE");
1444        printf("nOptions is %ld\n", (long)args.nOptions);
1445        for (i = 0; i < numOptions; i++)
1446            printf("    option[%2d] = '%s'\n",
1447                   i, args.options[i].optionString);
1448    }
1449
1450    r = ifn->CreateJavaVM(pvm, (void **)penv, &args);
1451    JLI_MemFree(options);
1452    return r == JNI_OK;
1453}
1454
1455static jclass helperClass = NULL;
1456
1457jclass
1458GetLauncherHelperClass(JNIEnv *env)
1459{
1460    if (helperClass == NULL) {
1461        NULL_CHECK0(helperClass = FindBootStrapClass(env,
1462                "sun/launcher/LauncherHelper"));
1463    }
1464    return helperClass;
1465}
1466
1467static jmethodID makePlatformStringMID = NULL;
1468/*
1469 * Returns a new Java string object for the specified platform string.
1470 */
1471static jstring
1472NewPlatformString(JNIEnv *env, char *s)
1473{
1474    int len = (int)JLI_StrLen(s);
1475    jbyteArray ary;
1476    jclass cls = GetLauncherHelperClass(env);
1477    NULL_CHECK0(cls);
1478    if (s == NULL)
1479        return 0;
1480
1481    ary = (*env)->NewByteArray(env, len);
1482    if (ary != 0) {
1483        jstring str = 0;
1484        (*env)->SetByteArrayRegion(env, ary, 0, len, (jbyte *)s);
1485        if (!(*env)->ExceptionOccurred(env)) {
1486            if (makePlatformStringMID == NULL) {
1487                NULL_CHECK0(makePlatformStringMID = (*env)->GetStaticMethodID(env,
1488                        cls, "makePlatformString", "(Z[B)Ljava/lang/String;"));
1489            }
1490            str = (*env)->CallStaticObjectMethod(env, cls,
1491                    makePlatformStringMID, USE_STDERR, ary);
1492            (*env)->DeleteLocalRef(env, ary);
1493            return str;
1494        }
1495    }
1496    return 0;
1497}
1498
1499/*
1500 * Returns a new array of Java string objects for the specified
1501 * array of platform strings.
1502 */
1503jobjectArray
1504NewPlatformStringArray(JNIEnv *env, char **strv, int strc)
1505{
1506    jarray cls;
1507    jarray ary;
1508    int i;
1509
1510    NULL_CHECK0(cls = FindBootStrapClass(env, "java/lang/String"));
1511    NULL_CHECK0(ary = (*env)->NewObjectArray(env, strc, cls, 0));
1512    CHECK_EXCEPTION_RETURN_VALUE(0);
1513    for (i = 0; i < strc; i++) {
1514        jstring str = NewPlatformString(env, *strv++);
1515        NULL_CHECK0(str);
1516        (*env)->SetObjectArrayElement(env, ary, i, str);
1517        (*env)->DeleteLocalRef(env, str);
1518    }
1519    return ary;
1520}
1521
1522/*
1523 * Loads a class and verifies that the main class is present and it is ok to
1524 * call it for more details refer to the java implementation.
1525 */
1526static jclass
1527LoadMainClass(JNIEnv *env, int mode, char *name)
1528{
1529    jmethodID mid;
1530    jstring str;
1531    jobject result;
1532    jlong start, end;
1533    jclass cls = GetLauncherHelperClass(env);
1534    NULL_CHECK0(cls);
1535    if (JLI_IsTraceLauncher()) {
1536        start = CounterGet();
1537    }
1538    NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1539                "checkAndLoadMain",
1540                "(ZILjava/lang/String;)Ljava/lang/Class;"));
1541
1542    NULL_CHECK0(str = NewPlatformString(env, name));
1543    NULL_CHECK0(result = (*env)->CallStaticObjectMethod(env, cls, mid,
1544                                                        USE_STDERR, mode, str));
1545
1546    if (JLI_IsTraceLauncher()) {
1547        end   = CounterGet();
1548        printf("%ld micro seconds to load main class\n",
1549               (long)(jint)Counter2Micros(end-start));
1550        printf("----%s----\n", JLDEBUG_ENV_ENTRY);
1551    }
1552
1553    return (jclass)result;
1554}
1555
1556static jclass
1557GetApplicationClass(JNIEnv *env)
1558{
1559    jmethodID mid;
1560    jclass cls = GetLauncherHelperClass(env);
1561    NULL_CHECK0(cls);
1562    NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1563                "getApplicationClass",
1564                "()Ljava/lang/Class;"));
1565
1566    return (*env)->CallStaticObjectMethod(env, cls, mid);
1567}
1568
1569static char* expandWildcardOnLongOpt(char* arg) {
1570    char *p, *value;
1571    size_t optLen, valueLen;
1572    p = JLI_StrChr(arg, '=');
1573
1574    if (p == NULL || p[1] == '\0') {
1575        JLI_ReportErrorMessage(ARG_ERROR1, arg);
1576        exit(1);
1577    }
1578    p++;
1579    value = (char *) JLI_WildcardExpandClasspath(p);
1580    if (p == value) {
1581        // no wildcard
1582        return arg;
1583    }
1584
1585    optLen = p - arg;
1586    valueLen = JLI_StrLen(value);
1587    p = JLI_MemAlloc(optLen + valueLen + 1);
1588    memcpy(p, arg, optLen);
1589    memcpy(p + optLen, value, valueLen);
1590    p[optLen + valueLen] = '\0';
1591    return p;
1592}
1593
1594/*
1595 * For tools, convert command line args thus:
1596 *   javac -cp foo:foo/"*" -J-ms32m ...
1597 *   java -ms32m -cp JLI_WildcardExpandClasspath(foo:foo/"*") ...
1598 *
1599 * Takes 4 parameters, and returns the populated arguments
1600 */
1601static void
1602TranslateApplicationArgs(int jargc, const char **jargv, int *pargc, char ***pargv)
1603{
1604    int argc = *pargc;
1605    char **argv = *pargv;
1606    int nargc = argc + jargc;
1607    char **nargv = JLI_MemAlloc((nargc + 1) * sizeof(char *));
1608    int i;
1609
1610    *pargc = nargc;
1611    *pargv = nargv;
1612
1613    /* Copy the VM arguments (i.e. prefixed with -J) */
1614    for (i = 0; i < jargc; i++) {
1615        const char *arg = jargv[i];
1616        if (arg[0] == '-' && arg[1] == 'J') {
1617            *nargv++ = ((arg + 2) == NULL) ? NULL : JLI_StringDup(arg + 2);
1618        }
1619    }
1620
1621    for (i = 0; i < argc; i++) {
1622        char *arg = argv[i];
1623        if (arg[0] == '-' && arg[1] == 'J') {
1624            if (arg[2] == '\0') {
1625                JLI_ReportErrorMessage(ARG_ERROR3);
1626                exit(1);
1627            }
1628            *nargv++ = arg + 2;
1629        }
1630    }
1631
1632    /* Copy the rest of the arguments */
1633    for (i = 0; i < jargc ; i++) {
1634        const char *arg = jargv[i];
1635        if (arg[0] != '-' || arg[1] != 'J') {
1636            *nargv++ = (arg == NULL) ? NULL : JLI_StringDup(arg);
1637        }
1638    }
1639    for (i = 0; i < argc; i++) {
1640        char *arg = argv[i];
1641        if (arg[0] == '-') {
1642            if (arg[1] == 'J')
1643                continue;
1644            if (IsWildCardEnabled()) {
1645                if (IsClassPathOption(arg) && i < argc - 1) {
1646                    *nargv++ = arg;
1647                    *nargv++ = (char *) JLI_WildcardExpandClasspath(argv[i+1]);
1648                    i++;
1649                    continue;
1650                }
1651                if (JLI_StrCCmp(arg, "--class-path=") == 0) {
1652                    *nargv++ = expandWildcardOnLongOpt(arg);
1653                    continue;
1654                }
1655            }
1656        }
1657        *nargv++ = arg;
1658    }
1659    *nargv = 0;
1660}
1661
1662/*
1663 * For our tools, we try to add 3 VM options:
1664 *      -Denv.class.path=<envcp>
1665 *      -Dapplication.home=<apphome>
1666 *      -Djava.class.path=<appcp>
1667 * <envcp>   is the user's setting of CLASSPATH -- for instance the user
1668 *           tells javac where to find binary classes through this environment
1669 *           variable.  Notice that users will be able to compile against our
1670 *           tools classes (sun.tools.javac.Main) only if they explicitly add
1671 *           tools.jar to CLASSPATH.
1672 * <apphome> is the directory where the application is installed.
1673 * <appcp>   is the classpath to where our apps' classfiles are.
1674 */
1675static jboolean
1676AddApplicationOptions(int cpathc, const char **cpathv)
1677{
1678    char *envcp, *appcp, *apphome;
1679    char home[MAXPATHLEN]; /* application home */
1680    char separator[] = { PATH_SEPARATOR, '\0' };
1681    int size, i;
1682
1683    {
1684        const char *s = getenv("CLASSPATH");
1685        if (s) {
1686            s = (char *) JLI_WildcardExpandClasspath(s);
1687            /* 40 for -Denv.class.path= */
1688            if (JLI_StrLen(s) + 40 > JLI_StrLen(s)) { // Safeguard from overflow
1689                envcp = (char *)JLI_MemAlloc(JLI_StrLen(s) + 40);
1690                sprintf(envcp, "-Denv.class.path=%s", s);
1691                AddOption(envcp, NULL);
1692            }
1693        }
1694    }
1695
1696    if (!GetApplicationHome(home, sizeof(home))) {
1697        JLI_ReportErrorMessage(CFG_ERROR5);
1698        return JNI_FALSE;
1699    }
1700
1701    /* 40 for '-Dapplication.home=' */
1702    apphome = (char *)JLI_MemAlloc(JLI_StrLen(home) + 40);
1703    sprintf(apphome, "-Dapplication.home=%s", home);
1704    AddOption(apphome, NULL);
1705
1706    /* How big is the application's classpath? */
1707    if (cpathc > 0) {
1708        size = 40;                                 /* 40: "-Djava.class.path=" */
1709        for (i = 0; i < cpathc; i++) {
1710            size += (int)JLI_StrLen(home) + (int)JLI_StrLen(cpathv[i]) + 1; /* 1: separator */
1711        }
1712        appcp = (char *)JLI_MemAlloc(size + 1);
1713        JLI_StrCpy(appcp, "-Djava.class.path=");
1714        for (i = 0; i < cpathc; i++) {
1715            JLI_StrCat(appcp, home);                        /* c:\program files\myapp */
1716            JLI_StrCat(appcp, cpathv[i]);           /* \lib\myapp.jar         */
1717            JLI_StrCat(appcp, separator);           /* ;                      */
1718        }
1719        appcp[JLI_StrLen(appcp)-1] = '\0';  /* remove trailing path separator */
1720        AddOption(appcp, NULL);
1721    }
1722    return JNI_TRUE;
1723}
1724
1725/*
1726 * inject the -Dsun.java.command pseudo property into the args structure
1727 * this pseudo property is used in the HotSpot VM to expose the
1728 * Java class name and arguments to the main method to the VM. The
1729 * HotSpot VM uses this pseudo property to store the Java class name
1730 * (or jar file name) and the arguments to the class's main method
1731 * to the instrumentation memory region. The sun.java.command pseudo
1732 * property is not exported by HotSpot to the Java layer.
1733 */
1734void
1735SetJavaCommandLineProp(char *what, int argc, char **argv)
1736{
1737
1738    int i = 0;
1739    size_t len = 0;
1740    char* javaCommand = NULL;
1741    char* dashDstr = "-Dsun.java.command=";
1742
1743    if (what == NULL) {
1744        /* unexpected, one of these should be set. just return without
1745         * setting the property
1746         */
1747        return;
1748    }
1749
1750    /* determine the amount of memory to allocate assuming
1751     * the individual components will be space separated
1752     */
1753    len = JLI_StrLen(what);
1754    for (i = 0; i < argc; i++) {
1755        len += JLI_StrLen(argv[i]) + 1;
1756    }
1757
1758    /* allocate the memory */
1759    javaCommand = (char*) JLI_MemAlloc(len + JLI_StrLen(dashDstr) + 1);
1760
1761    /* build the -D string */
1762    *javaCommand = '\0';
1763    JLI_StrCat(javaCommand, dashDstr);
1764    JLI_StrCat(javaCommand, what);
1765
1766    for (i = 0; i < argc; i++) {
1767        /* the components of the string are space separated. In
1768         * the case of embedded white space, the relationship of
1769         * the white space separated components to their true
1770         * positional arguments will be ambiguous. This issue may
1771         * be addressed in a future release.
1772         */
1773        JLI_StrCat(javaCommand, " ");
1774        JLI_StrCat(javaCommand, argv[i]);
1775    }
1776
1777    AddOption(javaCommand, NULL);
1778}
1779
1780/*
1781 * JVM would like to know if it's created by a standard Sun launcher, or by
1782 * user native application, the following property indicates the former.
1783 */
1784void
1785SetJavaLauncherProp() {
1786  AddOption("-Dsun.java.launcher=SUN_STANDARD", NULL);
1787}
1788
1789/*
1790 * Prints the version information from the java.version and other properties.
1791 */
1792static void
1793PrintJavaVersion(JNIEnv *env, jboolean extraLF)
1794{
1795    jclass ver;
1796    jmethodID print;
1797
1798    NULL_CHECK(ver = FindBootStrapClass(env, "java/lang/VersionProps"));
1799    NULL_CHECK(print = (*env)->GetStaticMethodID(env,
1800                                                 ver,
1801                                                 (extraLF == JNI_TRUE) ? "println" : "print",
1802                                                 "(Z)V"
1803                                                 )
1804              );
1805
1806    (*env)->CallStaticVoidMethod(env, ver, print, printTo);
1807}
1808
1809/*
1810 * Prints all the Java settings, see the java implementation for more details.
1811 */
1812static void
1813ShowSettings(JNIEnv *env, char *optString)
1814{
1815    jmethodID showSettingsID;
1816    jstring joptString;
1817    jclass cls = GetLauncherHelperClass(env);
1818    NULL_CHECK(cls);
1819    NULL_CHECK(showSettingsID = (*env)->GetStaticMethodID(env, cls,
1820            "showSettings", "(ZLjava/lang/String;JJJ)V"));
1821    NULL_CHECK(joptString = (*env)->NewStringUTF(env, optString));
1822    (*env)->CallStaticVoidMethod(env, cls, showSettingsID,
1823                                 USE_STDERR,
1824                                 joptString,
1825                                 (jlong)initialHeapSize,
1826                                 (jlong)maxHeapSize,
1827                                 (jlong)threadStackSize);
1828}
1829
1830/**
1831 * List modules supported by the runtime
1832 */
1833static void
1834ListModules(JNIEnv *env, char *optString)
1835{
1836    jmethodID listModulesID;
1837    jstring joptString = NULL;
1838    jclass cls = GetLauncherHelperClass(env);
1839    NULL_CHECK(cls);
1840    NULL_CHECK(listModulesID = (*env)->GetStaticMethodID(env, cls,
1841            "listModules", "(ZLjava/lang/String;)V"));
1842    NULL_CHECK(joptString = (*env)->NewStringUTF(env, optString));
1843    (*env)->CallStaticVoidMethod(env, cls, listModulesID,
1844                                 USE_STDOUT,
1845                                 joptString);
1846}
1847
1848/*
1849 * Prints default usage or the Xusage message, see sun.launcher.LauncherHelper.java
1850 */
1851static void
1852PrintUsage(JNIEnv* env, jboolean doXUsage)
1853{
1854  jmethodID initHelp, vmSelect, vmSynonym, printHelp, printXUsageMessage;
1855  jstring jprogname, vm1, vm2;
1856  int i;
1857  jclass cls = GetLauncherHelperClass(env);
1858  NULL_CHECK(cls);
1859  if (doXUsage) {
1860    NULL_CHECK(printXUsageMessage = (*env)->GetStaticMethodID(env, cls,
1861                                        "printXUsageMessage", "(Z)V"));
1862    (*env)->CallStaticVoidMethod(env, cls, printXUsageMessage, printTo);
1863  } else {
1864    NULL_CHECK(initHelp = (*env)->GetStaticMethodID(env, cls,
1865                                        "initHelpMessage", "(Ljava/lang/String;)V"));
1866
1867    NULL_CHECK(vmSelect = (*env)->GetStaticMethodID(env, cls, "appendVmSelectMessage",
1868                                        "(Ljava/lang/String;Ljava/lang/String;)V"));
1869
1870    NULL_CHECK(vmSynonym = (*env)->GetStaticMethodID(env, cls,
1871                                        "appendVmSynonymMessage",
1872                                        "(Ljava/lang/String;Ljava/lang/String;)V"));
1873
1874    NULL_CHECK(printHelp = (*env)->GetStaticMethodID(env, cls,
1875                                        "printHelpMessage", "(Z)V"));
1876
1877    NULL_CHECK(jprogname = (*env)->NewStringUTF(env, _program_name));
1878
1879    /* Initialize the usage message with the usual preamble */
1880    (*env)->CallStaticVoidMethod(env, cls, initHelp, jprogname);
1881    CHECK_EXCEPTION_RETURN();
1882
1883
1884    /* Assemble the other variant part of the usage */
1885    for (i=1; i<knownVMsCount; i++) {
1886      if (knownVMs[i].flag == VM_KNOWN) {
1887        NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
1888        NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].name+1));
1889        (*env)->CallStaticVoidMethod(env, cls, vmSelect, vm1, vm2);
1890        CHECK_EXCEPTION_RETURN();
1891      }
1892    }
1893    for (i=1; i<knownVMsCount; i++) {
1894      if (knownVMs[i].flag == VM_ALIASED_TO) {
1895        NULL_CHECK(vm1 =  (*env)->NewStringUTF(env, knownVMs[i].name));
1896        NULL_CHECK(vm2 =  (*env)->NewStringUTF(env, knownVMs[i].alias+1));
1897        (*env)->CallStaticVoidMethod(env, cls, vmSynonym, vm1, vm2);
1898        CHECK_EXCEPTION_RETURN();
1899      }
1900    }
1901
1902    /* Complete the usage message and print to stderr*/
1903    (*env)->CallStaticVoidMethod(env, cls, printHelp, printTo);
1904  }
1905  return;
1906}
1907
1908/*
1909 * Read the jvm.cfg file and fill the knownJVMs[] array.
1910 *
1911 * The functionality of the jvm.cfg file is subject to change without
1912 * notice and the mechanism will be removed in the future.
1913 *
1914 * The lexical structure of the jvm.cfg file is as follows:
1915 *
1916 *     jvmcfg         :=  { vmLine }
1917 *     vmLine         :=  knownLine
1918 *                    |   aliasLine
1919 *                    |   warnLine
1920 *                    |   ignoreLine
1921 *                    |   errorLine
1922 *                    |   predicateLine
1923 *                    |   commentLine
1924 *     knownLine      :=  flag  "KNOWN"                  EOL
1925 *     warnLine       :=  flag  "WARN"                   EOL
1926 *     ignoreLine     :=  flag  "IGNORE"                 EOL
1927 *     errorLine      :=  flag  "ERROR"                  EOL
1928 *     aliasLine      :=  flag  "ALIASED_TO"       flag  EOL
1929 *     predicateLine  :=  flag  "IF_SERVER_CLASS"  flag  EOL
1930 *     commentLine    :=  "#" text                       EOL
1931 *     flag           :=  "-" identifier
1932 *
1933 * The semantics are that when someone specifies a flag on the command line:
1934 * - if the flag appears on a knownLine, then the identifier is used as
1935 *   the name of the directory holding the JVM library (the name of the JVM).
1936 * - if the flag appears as the first flag on an aliasLine, the identifier
1937 *   of the second flag is used as the name of the JVM.
1938 * - if the flag appears on a warnLine, the identifier is used as the
1939 *   name of the JVM, but a warning is generated.
1940 * - if the flag appears on an ignoreLine, the identifier is recognized as the
1941 *   name of a JVM, but the identifier is ignored and the default vm used
1942 * - if the flag appears on an errorLine, an error is generated.
1943 * - if the flag appears as the first flag on a predicateLine, and
1944 *   the machine on which you are running passes the predicate indicated,
1945 *   then the identifier of the second flag is used as the name of the JVM,
1946 *   otherwise the identifier of the first flag is used as the name of the JVM.
1947 * If no flag is given on the command line, the first vmLine of the jvm.cfg
1948 * file determines the name of the JVM.
1949 * PredicateLines are only interpreted on first vmLine of a jvm.cfg file,
1950 * since they only make sense if someone hasn't specified the name of the
1951 * JVM on the command line.
1952 *
1953 * The intent of the jvm.cfg file is to allow several JVM libraries to
1954 * be installed in different subdirectories of a single JRE installation,
1955 * for space-savings and convenience in testing.
1956 * The intent is explicitly not to provide a full aliasing or predicate
1957 * mechanism.
1958 */
1959jint
1960ReadKnownVMs(const char *jvmCfgName, jboolean speculative)
1961{
1962    FILE *jvmCfg;
1963    char line[MAXPATHLEN+20];
1964    int cnt = 0;
1965    int lineno = 0;
1966    jlong start, end;
1967    int vmType;
1968    char *tmpPtr;
1969    char *altVMName = NULL;
1970    char *serverClassVMName = NULL;
1971    static char *whiteSpace = " \t";
1972    if (JLI_IsTraceLauncher()) {
1973        start = CounterGet();
1974    }
1975
1976    jvmCfg = fopen(jvmCfgName, "r");
1977    if (jvmCfg == NULL) {
1978      if (!speculative) {
1979        JLI_ReportErrorMessage(CFG_ERROR6, jvmCfgName);
1980        exit(1);
1981      } else {
1982        return -1;
1983      }
1984    }
1985    while (fgets(line, sizeof(line), jvmCfg) != NULL) {
1986        vmType = VM_UNKNOWN;
1987        lineno++;
1988        if (line[0] == '#')
1989            continue;
1990        if (line[0] != '-') {
1991            JLI_ReportErrorMessage(CFG_WARN2, lineno, jvmCfgName);
1992        }
1993        if (cnt >= knownVMsLimit) {
1994            GrowKnownVMs(cnt);
1995        }
1996        line[JLI_StrLen(line)-1] = '\0'; /* remove trailing newline */
1997        tmpPtr = line + JLI_StrCSpn(line, whiteSpace);
1998        if (*tmpPtr == 0) {
1999            JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2000        } else {
2001            /* Null-terminate this string for JLI_StringDup below */
2002            *tmpPtr++ = 0;
2003            tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
2004            if (*tmpPtr == 0) {
2005                JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2006            } else {
2007                if (!JLI_StrCCmp(tmpPtr, "KNOWN")) {
2008                    vmType = VM_KNOWN;
2009                } else if (!JLI_StrCCmp(tmpPtr, "ALIASED_TO")) {
2010                    tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
2011                    if (*tmpPtr != 0) {
2012                        tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace);
2013                    }
2014                    if (*tmpPtr == 0) {
2015                        JLI_ReportErrorMessage(CFG_WARN3, lineno, jvmCfgName);
2016                    } else {
2017                        /* Null terminate altVMName */
2018                        altVMName = tmpPtr;
2019                        tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace);
2020                        *tmpPtr = 0;
2021                        vmType = VM_ALIASED_TO;
2022                    }
2023                } else if (!JLI_StrCCmp(tmpPtr, "WARN")) {
2024                    vmType = VM_WARN;
2025                } else if (!JLI_StrCCmp(tmpPtr, "IGNORE")) {
2026                    vmType = VM_IGNORE;
2027                } else if (!JLI_StrCCmp(tmpPtr, "ERROR")) {
2028                    vmType = VM_ERROR;
2029                } else if (!JLI_StrCCmp(tmpPtr, "IF_SERVER_CLASS")) {
2030                    /* ignored */
2031                } else {
2032                    JLI_ReportErrorMessage(CFG_WARN5, lineno, &jvmCfgName[0]);
2033                    vmType = VM_KNOWN;
2034                }
2035            }
2036        }
2037
2038        JLI_TraceLauncher("jvm.cfg[%d] = ->%s<-\n", cnt, line);
2039        if (vmType != VM_UNKNOWN) {
2040            knownVMs[cnt].name = JLI_StringDup(line);
2041            knownVMs[cnt].flag = vmType;
2042            switch (vmType) {
2043            default:
2044                break;
2045            case VM_ALIASED_TO:
2046                knownVMs[cnt].alias = JLI_StringDup(altVMName);
2047                JLI_TraceLauncher("    name: %s  vmType: %s  alias: %s\n",
2048                   knownVMs[cnt].name, "VM_ALIASED_TO", knownVMs[cnt].alias);
2049                break;
2050            }
2051            cnt++;
2052        }
2053    }
2054    fclose(jvmCfg);
2055    knownVMsCount = cnt;
2056
2057    if (JLI_IsTraceLauncher()) {
2058        end   = CounterGet();
2059        printf("%ld micro seconds to parse jvm.cfg\n",
2060               (long)(jint)Counter2Micros(end-start));
2061    }
2062
2063    return cnt;
2064}
2065
2066
2067static void
2068GrowKnownVMs(int minimum)
2069{
2070    struct vmdesc* newKnownVMs;
2071    int newMax;
2072
2073    newMax = (knownVMsLimit == 0 ? INIT_MAX_KNOWN_VMS : (2 * knownVMsLimit));
2074    if (newMax <= minimum) {
2075        newMax = minimum;
2076    }
2077    newKnownVMs = (struct vmdesc*) JLI_MemAlloc(newMax * sizeof(struct vmdesc));
2078    if (knownVMs != NULL) {
2079        memcpy(newKnownVMs, knownVMs, knownVMsLimit * sizeof(struct vmdesc));
2080    }
2081    JLI_MemFree(knownVMs);
2082    knownVMs = newKnownVMs;
2083    knownVMsLimit = newMax;
2084}
2085
2086
2087/* Returns index of VM or -1 if not found */
2088static int
2089KnownVMIndex(const char* name)
2090{
2091    int i;
2092    if (JLI_StrCCmp(name, "-J") == 0) name += 2;
2093    for (i = 0; i < knownVMsCount; i++) {
2094        if (!JLI_StrCmp(name, knownVMs[i].name)) {
2095            return i;
2096        }
2097    }
2098    return -1;
2099}
2100
2101static void
2102FreeKnownVMs()
2103{
2104    int i;
2105    for (i = 0; i < knownVMsCount; i++) {
2106        JLI_MemFree(knownVMs[i].name);
2107        knownVMs[i].name = NULL;
2108    }
2109    JLI_MemFree(knownVMs);
2110}
2111
2112/*
2113 * Displays the splash screen according to the jar file name
2114 * and image file names stored in environment variables
2115 */
2116void
2117ShowSplashScreen()
2118{
2119    const char *jar_name = getenv(SPLASH_JAR_ENV_ENTRY);
2120    const char *file_name = getenv(SPLASH_FILE_ENV_ENTRY);
2121    int data_size;
2122    void *image_data = NULL;
2123    float scale_factor = 1;
2124    char *scaled_splash_name = NULL;
2125    jboolean isImageScaled = JNI_FALSE;
2126    size_t maxScaledImgNameLength = 0;
2127    if (file_name == NULL){
2128        return;
2129    }
2130    maxScaledImgNameLength = DoSplashGetScaledImgNameMaxPstfixLen(file_name);
2131
2132    scaled_splash_name = JLI_MemAlloc(
2133                            maxScaledImgNameLength * sizeof(char));
2134    isImageScaled = DoSplashGetScaledImageName(jar_name, file_name,
2135                            &scale_factor,
2136                            scaled_splash_name, maxScaledImgNameLength);
2137    if (jar_name) {
2138
2139        if (isImageScaled) {
2140            image_data = JLI_JarUnpackFile(
2141                    jar_name, scaled_splash_name, &data_size);
2142        }
2143
2144        if (!image_data) {
2145            scale_factor = 1;
2146            image_data = JLI_JarUnpackFile(
2147                            jar_name, file_name, &data_size);
2148        }
2149        if (image_data) {
2150            DoSplashInit();
2151            DoSplashSetScaleFactor(scale_factor);
2152            DoSplashLoadMemory(image_data, data_size);
2153            JLI_MemFree(image_data);
2154        }
2155    } else {
2156        DoSplashInit();
2157        if (isImageScaled) {
2158            DoSplashSetScaleFactor(scale_factor);
2159            DoSplashLoadFile(scaled_splash_name);
2160        } else {
2161            DoSplashLoadFile(file_name);
2162        }
2163    }
2164    JLI_MemFree(scaled_splash_name);
2165
2166    DoSplashSetFileJarName(file_name, jar_name);
2167
2168    /*
2169     * Done with all command line processing and potential re-execs so
2170     * clean up the environment.
2171     */
2172    (void)UnsetEnv(ENV_ENTRY);
2173    (void)UnsetEnv(SPLASH_FILE_ENV_ENTRY);
2174    (void)UnsetEnv(SPLASH_JAR_ENV_ENTRY);
2175
2176    JLI_MemFree(splash_jar_entry);
2177    JLI_MemFree(splash_file_entry);
2178
2179}
2180
2181const char*
2182GetFullVersion()
2183{
2184    return _fVersion;
2185}
2186
2187const char*
2188GetProgramName()
2189{
2190    return _program_name;
2191}
2192
2193const char*
2194GetLauncherName()
2195{
2196    return _launcher_name;
2197}
2198
2199jboolean
2200IsJavaArgs()
2201{
2202    return _is_java_args;
2203}
2204
2205static jboolean
2206IsWildCardEnabled()
2207{
2208    return _wc_enabled;
2209}
2210
2211int
2212ContinueInNewThread(InvocationFunctions* ifn, jlong threadStackSize,
2213                    int argc, char **argv,
2214                    int mode, char *what, int ret)
2215{
2216
2217    /*
2218     * If user doesn't specify stack size, check if VM has a preference.
2219     * Note that HotSpot no longer supports JNI_VERSION_1_1 but it will
2220     * return its default stack size through the init args structure.
2221     */
2222    if (threadStackSize == 0) {
2223      struct JDK1_1InitArgs args1_1;
2224      memset((void*)&args1_1, 0, sizeof(args1_1));
2225      args1_1.version = JNI_VERSION_1_1;
2226      ifn->GetDefaultJavaVMInitArgs(&args1_1);  /* ignore return value */
2227      if (args1_1.javaStackSize > 0) {
2228         threadStackSize = args1_1.javaStackSize;
2229      }
2230    }
2231
2232    { /* Create a new thread to create JVM and invoke main method */
2233      JavaMainArgs args;
2234      int rslt;
2235
2236      args.argc = argc;
2237      args.argv = argv;
2238      args.mode = mode;
2239      args.what = what;
2240      args.ifn = *ifn;
2241
2242      rslt = ContinueInNewThread0(JavaMain, threadStackSize, (void*)&args);
2243      /* If the caller has deemed there is an error we
2244       * simply return that, otherwise we return the value of
2245       * the callee
2246       */
2247      return (ret != 0) ? ret : rslt;
2248    }
2249}
2250
2251static void
2252DumpState()
2253{
2254    if (!JLI_IsTraceLauncher()) return ;
2255    printf("Launcher state:\n");
2256    printf("\tFirst application arg index: %d\n", JLI_GetAppArgIndex());
2257    printf("\tdebug:%s\n", (JLI_IsTraceLauncher() == JNI_TRUE) ? "on" : "off");
2258    printf("\tjavargs:%s\n", (_is_java_args == JNI_TRUE) ? "on" : "off");
2259    printf("\tprogram name:%s\n", GetProgramName());
2260    printf("\tlauncher name:%s\n", GetLauncherName());
2261    printf("\tjavaw:%s\n", (IsJavaw() == JNI_TRUE) ? "on" : "off");
2262    printf("\tfullversion:%s\n", GetFullVersion());
2263}
2264
2265/*
2266 * Return JNI_TRUE for an option string that has no effect but should
2267 * _not_ be passed on to the vm; return JNI_FALSE otherwise.  On
2268 * Solaris SPARC, this screening needs to be done if:
2269 *    -d32 or -d64 is passed to a binary with an unmatched data model
2270 *    (the exec in CreateExecutionEnvironment removes -d<n> options and points the
2271 *    exec to the proper binary).  In the case of when the data model and the
2272 *    requested version is matched, an exec would not occur, and these options
2273 *    were erroneously passed to the vm.
2274 */
2275jboolean
2276RemovableOption(char * option)
2277{
2278  /*
2279   * Unconditionally remove both -d32 and -d64 options since only
2280   * the last such options has an effect; e.g.
2281   * java -d32 -d64 -d32 -version
2282   * is equivalent to
2283   * java -d32 -version
2284   */
2285
2286  if( (JLI_StrCCmp(option, "-d32")  == 0 ) ||
2287      (JLI_StrCCmp(option, "-d64")  == 0 ) )
2288    return JNI_TRUE;
2289  else
2290    return JNI_FALSE;
2291}
2292
2293/*
2294 * A utility procedure to always print to stderr
2295 */
2296void
2297JLI_ReportMessage(const char* fmt, ...)
2298{
2299    va_list vl;
2300    va_start(vl, fmt);
2301    vfprintf(stderr, fmt, vl);
2302    fprintf(stderr, "\n");
2303    va_end(vl);
2304}
2305
2306/*
2307 * A utility procedure to always print to stdout
2308 */
2309void
2310JLI_ShowMessage(const char* fmt, ...)
2311{
2312    va_list vl;
2313    va_start(vl, fmt);
2314    vfprintf(stdout, fmt, vl);
2315    fprintf(stdout, "\n");
2316    va_end(vl);
2317}
2318