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