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