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