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