blob: f252e0b1b3821815d3612a689ccb71fa5efabebe [file] [log] [blame]
duke6e45e102007-12-01 00:00:00 +00001/*
2 * Copyright 1997-2007 Sun Microsystems, Inc. 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. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
25
26#include <windows.h>
27#include <io.h>
28#include <process.h>
29#include <stdlib.h>
30#include <stdio.h>
31#include <stdarg.h>
32#include <string.h>
33#include <sys/types.h>
34#include <sys/stat.h>
35#include <wtypes.h>
ksrini52cded22008-03-06 07:51:28 -080036#include <commctrl.h>
duke6e45e102007-12-01 00:00:00 +000037
38#include <jni.h>
39#include "java.h"
40#include "version_comp.h"
41
42#define JVM_DLL "jvm.dll"
43#define JAVA_DLL "java.dll"
44#define CRT_DLL "msvcr71.dll"
45
46/*
47 * Prototypes.
48 */
49static jboolean GetPublicJREHome(char *path, jint pathsize);
50static jboolean GetJVMPath(const char *jrepath, const char *jvmtype,
51 char *jvmpath, jint jvmpathsize);
52static jboolean GetJREPath(char *path, jint pathsize);
53
54static jboolean _isjavaw = JNI_FALSE;
55
duke6e45e102007-12-01 00:00:00 +000056
57jboolean
58IsJavaw()
59{
60 return _isjavaw;
61}
62
63/*
64 * Returns the arch path, to get the current arch use the
65 * macro GetArch, nbits here is ignored for now.
66 */
67const char *
68GetArchPath(int nbits)
69{
70#ifdef _M_AMD64
71 return "amd64";
72#elif defined(_M_IA64)
73 return "ia64";
74#else
75 return "i386";
76#endif
77}
78
79/*
80 *
81 */
82void
83CreateExecutionEnvironment(int *_argc,
84 char ***_argv,
85 char jrepath[],
86 jint so_jrepath,
87 char jvmpath[],
88 jint so_jvmpath,
89 char **original_argv) {
90 char * jvmtype;
91 int i = 0;
92 char** pargv = *_argv;
93 int running = CURRENT_DATA_MODEL;
94
95 int wanted = running;
96
97 for (i = 0; i < *_argc ; i++) {
98 if (JLI_StrCmp(pargv[i], "-J-d64") == 0 || JLI_StrCmp(pargv[i], "-d64") == 0) {
99 wanted = 64;
100 continue;
101 }
102 if (JLI_StrCmp(pargv[i], "-J-d32") == 0 || JLI_StrCmp(pargv[i], "-d32") == 0) {
103 wanted = 32;
104 continue;
105 }
106 }
107 if (running != wanted) {
108 ReportErrorMessage(JRE_ERROR2, wanted);
109 exit(1);
110 }
111
112 /* Find out where the JRE is that we will be using. */
113 if (!GetJREPath(jrepath, so_jrepath)) {
114 ReportErrorMessage(JRE_ERROR1);
115 exit(2);
116 }
117
118 /* Find the specified JVM type */
119 if (ReadKnownVMs(jrepath, (char*)GetArch(), JNI_FALSE) < 1) {
120 ReportErrorMessage(CFG_ERROR7);
121 exit(1);
122 }
123 jvmtype = CheckJvmType(_argc, _argv, JNI_FALSE);
124
125 jvmpath[0] = '\0';
126 if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath)) {
127 ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath);
128 exit(4);
129 }
130 /* If we got here, jvmpath has been correctly initialized. */
131
132}
133
134/*
135 * Find path to JRE based on .exe's location or registry settings.
136 */
137jboolean
138GetJREPath(char *path, jint pathsize)
139{
140 char javadll[MAXPATHLEN];
141 struct stat s;
142
143 if (GetApplicationHome(path, pathsize)) {
144 /* Is JRE co-located with the application? */
145 sprintf(javadll, "%s\\bin\\" JAVA_DLL, path);
146 if (stat(javadll, &s) == 0) {
147 goto found;
148 }
149
150 /* Does this app ship a private JRE in <apphome>\jre directory? */
151 sprintf(javadll, "%s\\jre\\bin\\" JAVA_DLL, path);
152 if (stat(javadll, &s) == 0) {
153 JLI_StrCat(path, "\\jre");
154 goto found;
155 }
156 }
157
158 /* Look for a public JRE on this machine. */
159 if (GetPublicJREHome(path, pathsize)) {
160 goto found;
161 }
162
163 ReportErrorMessage(JRE_ERROR8 JAVA_DLL);
164 return JNI_FALSE;
165
166 found:
167 JLI_TraceLauncher("JRE path is %s\n", path);
168 return JNI_TRUE;
169}
170
171/*
172 * Given a JRE location and a JVM type, construct what the name the
173 * JVM shared library will be. Return true, if such a library
174 * exists, false otherwise.
175 */
176static jboolean
177GetJVMPath(const char *jrepath, const char *jvmtype,
178 char *jvmpath, jint jvmpathsize)
179{
180 struct stat s;
181 if (JLI_StrChr(jvmtype, '/') || JLI_StrChr(jvmtype, '\\')) {
182 sprintf(jvmpath, "%s\\" JVM_DLL, jvmtype);
183 } else {
184 sprintf(jvmpath, "%s\\bin\\%s\\" JVM_DLL, jrepath, jvmtype);
185 }
186 if (stat(jvmpath, &s) == 0) {
187 return JNI_TRUE;
188 } else {
189 return JNI_FALSE;
190 }
191}
192
193/*
194 * Load a jvm from "jvmpath" and initialize the invocation functions.
195 */
196jboolean
197LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)
198{
199 HINSTANCE handle;
200 char crtpath[MAXPATHLEN];
201
202 JLI_TraceLauncher("JVM path is %s\n", jvmpath);
203
204 /*
205 * The Microsoft C Runtime Library needs to be loaded first. A copy is
206 * assumed to be present in the "JRE path" directory. If it is not found
207 * there (or "JRE path" fails to resolve), skip the explicit load and let
208 * nature take its course, which is likely to be a failure to execute.
209 */
210 if (GetJREPath(crtpath, MAXPATHLEN)) {
211 (void)JLI_StrCat(crtpath, "\\bin\\" CRT_DLL); /* Add crt dll */
212 JLI_TraceLauncher("CRT path is %s\n", crtpath);
213 if (_access(crtpath, 0) == 0) {
214 if (LoadLibrary(crtpath) == 0) {
215 ReportErrorMessage(DLL_ERROR4, crtpath);
216 return JNI_FALSE;
217 }
218 }
219 }
220
221 /* Load the Java VM DLL */
222 if ((handle = LoadLibrary(jvmpath)) == 0) {
223 ReportErrorMessage(DLL_ERROR4, (char *)jvmpath);
224 return JNI_FALSE;
225 }
226
227 /* Now get the function addresses */
228 ifn->CreateJavaVM =
229 (void *)GetProcAddress(handle, "JNI_CreateJavaVM");
230 ifn->GetDefaultJavaVMInitArgs =
231 (void *)GetProcAddress(handle, "JNI_GetDefaultJavaVMInitArgs");
232 if (ifn->CreateJavaVM == 0 || ifn->GetDefaultJavaVMInitArgs == 0) {
233 ReportErrorMessage(JNI_ERROR1, (char *)jvmpath);
234 return JNI_FALSE;
235 }
236
237 return JNI_TRUE;
238}
239
240/*
241 * If app is "c:\foo\bin\javac", then put "c:\foo" into buf.
242 */
243jboolean
244GetApplicationHome(char *buf, jint bufsize)
245{
246 char *cp;
247 GetModuleFileName(0, buf, bufsize);
248 *JLI_StrRChr(buf, '\\') = '\0'; /* remove .exe file name */
249 if ((cp = JLI_StrRChr(buf, '\\')) == 0) {
250 /* This happens if the application is in a drive root, and
251 * there is no bin directory. */
252 buf[0] = '\0';
253 return JNI_FALSE;
254 }
255 *cp = '\0'; /* remove the bin\ part */
256 return JNI_TRUE;
257}
258
259/*
260 * Helpers to look in the registry for a public JRE.
261 */
262 /* Same for 1.5.0, 1.5.1, 1.5.2 etc. */
263#define JRE_KEY "Software\\JavaSoft\\Java Runtime Environment"
264
265static jboolean
266GetStringFromRegistry(HKEY key, const char *name, char *buf, jint bufsize)
267{
268 DWORD type, size;
269
270 if (RegQueryValueEx(key, name, 0, &type, 0, &size) == 0
271 && type == REG_SZ
272 && (size < (unsigned int)bufsize)) {
273 if (RegQueryValueEx(key, name, 0, 0, buf, &size) == 0) {
274 return JNI_TRUE;
275 }
276 }
277 return JNI_FALSE;
278}
279
280static jboolean
281GetPublicJREHome(char *buf, jint bufsize)
282{
283 HKEY key, subkey;
284 char version[MAXPATHLEN];
285
286 /*
287 * Note: There is a very similar implementation of the following
288 * registry reading code in the Windows java control panel (javacp.cpl).
289 * If there are bugs here, a similar bug probably exists there. Hence,
290 * changes here require inspection there.
291 */
292
293 /* Find the current version of the JRE */
294 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, JRE_KEY, 0, KEY_READ, &key) != 0) {
295 ReportErrorMessage(REG_ERROR1, JRE_KEY);
296 return JNI_FALSE;
297 }
298
299 if (!GetStringFromRegistry(key, "CurrentVersion",
300 version, sizeof(version))) {
301 ReportErrorMessage(REG_ERROR2, JRE_KEY);
302 RegCloseKey(key);
303 return JNI_FALSE;
304 }
305
306 if (JLI_StrCmp(version, GetDotVersion()) != 0) {
307 ReportErrorMessage(REG_ERROR3, JRE_KEY, version, GetDotVersion()
308 );
309 RegCloseKey(key);
310 return JNI_FALSE;
311 }
312
313 /* Find directory where the current version is installed. */
314 if (RegOpenKeyEx(key, version, 0, KEY_READ, &subkey) != 0) {
315 ReportErrorMessage(REG_ERROR1, JRE_KEY, version);
316 RegCloseKey(key);
317 return JNI_FALSE;
318 }
319
320 if (!GetStringFromRegistry(subkey, "JavaHome", buf, bufsize)) {
321 ReportErrorMessage(REG_ERROR4, JRE_KEY, version);
322 RegCloseKey(key);
323 RegCloseKey(subkey);
324 return JNI_FALSE;
325 }
326
327 if (JLI_IsTraceLauncher()) {
328 char micro[MAXPATHLEN];
329 if (!GetStringFromRegistry(subkey, "MicroVersion", micro,
330 sizeof(micro))) {
331 printf("Warning: Can't read MicroVersion\n");
332 micro[0] = '\0';
333 }
334 printf("Version major.minor.micro = %s.%s\n", version, micro);
335 }
336
337 RegCloseKey(key);
338 RegCloseKey(subkey);
339 return JNI_TRUE;
340}
341
342/*
343 * Support for doing cheap, accurate interval timing.
344 */
345static jboolean counterAvailable = JNI_FALSE;
346static jboolean counterInitialized = JNI_FALSE;
347static LARGE_INTEGER counterFrequency;
348
349jlong CounterGet()
350{
351 LARGE_INTEGER count;
352
353 if (!counterInitialized) {
354 counterAvailable = QueryPerformanceFrequency(&counterFrequency);
355 counterInitialized = JNI_TRUE;
356 }
357 if (!counterAvailable) {
358 return 0;
359 }
360 QueryPerformanceCounter(&count);
361 return (jlong)(count.QuadPart);
362}
363
364jlong Counter2Micros(jlong counts)
365{
366 if (!counterAvailable || !counterInitialized) {
367 return 0;
368 }
369 return (counts * 1000 * 1000)/counterFrequency.QuadPart;
370}
371
372void
373ReportErrorMessage(const char* fmt, ...) {
374 va_list vl;
375 va_start(vl,fmt);
376
377 if (IsJavaw()) {
378 char *message;
379
380 /* get the length of the string we need */
381 int n = _vscprintf(fmt, vl);
382
383 message = (char *)JLI_MemAlloc(n + 1);
384 _vsnprintf(message, n, fmt, vl);
385 message[n]='\0';
386 MessageBox(NULL, message, "Java Virtual Machine Launcher",
387 (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
388 JLI_MemFree(message);
389 } else {
390 vfprintf(stderr, fmt, vl);
391 fprintf(stderr, "\n");
392 }
393 va_end(vl);
394}
395
396/*
397 * Just like ReportErrorMessage, except that it concatenates the system
398 * error message if any, its upto the calling routine to correctly
399 * format the separation of the messages.
400 */
401void
402ReportErrorMessageSys(const char *fmt, ...)
403{
404 va_list vl;
405
406 int save_errno = errno;
407 DWORD errval;
408 jboolean freeit = JNI_FALSE;
409 char *errtext = NULL;
410
411 va_start(vl, fmt);
412
413 if ((errval = GetLastError()) != 0) { /* Platform SDK / DOS Error */
414 int n = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|
415 FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_ALLOCATE_BUFFER,
416 NULL, errval, 0, (LPTSTR)&errtext, 0, NULL);
417 if (errtext == NULL || n == 0) { /* Paranoia check */
418 errtext = "";
419 n = 0;
420 } else {
421 freeit = JNI_TRUE;
422 if (n > 2) { /* Drop final CR, LF */
423 if (errtext[n - 1] == '\n') n--;
424 if (errtext[n - 1] == '\r') n--;
425 errtext[n] = '\0';
426 }
427 }
428 } else { /* C runtime error that has no corresponding DOS error code */
429 errtext = strerror(save_errno);
430 }
431
432 if (IsJavaw()) {
433 char *message;
434 int mlen;
435 /* get the length of the string we need */
436 int len = mlen = _vscprintf(fmt, vl) + 1;
437 if (freeit) {
438 mlen += JLI_StrLen(errtext);
439 }
440
441 message = (char *)JLI_MemAlloc(mlen);
442 _vsnprintf(message, len, fmt, vl);
443 message[len]='\0';
444
445 if (freeit) {
446 JLI_StrCat(message, errtext);
447 }
448
449 MessageBox(NULL, message, "Java Virtual Machine Launcher",
450 (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
451
452 JLI_MemFree(message);
453 } else {
454 vfprintf(stderr, fmt, vl);
455 if (freeit) {
456 fprintf(stderr, "%s", errtext);
457 }
458 }
459 if (freeit) {
460 (void)LocalFree((HLOCAL)errtext);
461 }
462 va_end(vl);
463}
464
465void ReportExceptionDescription(JNIEnv * env) {
466 if (IsJavaw()) {
467 /*
468 * This code should be replaced by code which opens a window with
469 * the exception detail message, for now atleast put a dialog up.
470 */
471 MessageBox(NULL, "A Java Exception has occurred.", "Java Virtual Machine Launcher",
472 (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
473 } else {
474 (*env)->ExceptionDescribe(env);
475 }
476}
477
478jboolean
479ServerClassMachine() {
480 return (GetErgoPolicy() == ALWAYS_SERVER_CLASS) ? JNI_TRUE : JNI_FALSE;
481}
482
483/*
484 * Determine if there is an acceptable JRE in the registry directory top_key.
485 * Upon locating the "best" one, return a fully qualified path to it.
486 * "Best" is defined as the most advanced JRE meeting the constraints
487 * contained in the manifest_info. If no JRE in this directory meets the
488 * constraints, return NULL.
489 *
490 * It doesn't matter if we get an error reading the registry, or we just
491 * don't find anything interesting in the directory. We just return NULL
492 * in either case.
493 */
494static char *
495ProcessDir(manifest_info* info, HKEY top_key) {
496 DWORD index = 0;
497 HKEY ver_key;
498 char name[MAXNAMELEN];
499 int len;
500 char *best = NULL;
501
502 /*
503 * Enumerate "<top_key>/SOFTWARE/JavaSoft/Java Runtime Environment"
504 * searching for the best available version.
505 */
506 while (RegEnumKey(top_key, index, name, MAXNAMELEN) == ERROR_SUCCESS) {
507 index++;
508 if (JLI_AcceptableRelease(name, info->jre_version))
509 if ((best == NULL) || (JLI_ExactVersionId(name, best) > 0)) {
510 if (best != NULL)
511 JLI_MemFree(best);
512 best = JLI_StringDup(name);
513 }
514 }
515
516 /*
517 * Extract "JavaHome" from the "best" registry directory and return
518 * that path. If no appropriate version was located, or there is an
519 * error in extracting the "JavaHome" string, return null.
520 */
521 if (best == NULL)
522 return (NULL);
523 else {
524 if (RegOpenKeyEx(top_key, best, 0, KEY_READ, &ver_key)
525 != ERROR_SUCCESS) {
526 JLI_MemFree(best);
527 if (ver_key != NULL)
528 RegCloseKey(ver_key);
529 return (NULL);
530 }
531 JLI_MemFree(best);
532 len = MAXNAMELEN;
533 if (RegQueryValueEx(ver_key, "JavaHome", NULL, NULL, (LPBYTE)name, &len)
534 != ERROR_SUCCESS) {
535 if (ver_key != NULL)
536 RegCloseKey(ver_key);
537 return (NULL);
538 }
539 if (ver_key != NULL)
540 RegCloseKey(ver_key);
541 return (JLI_StringDup(name));
542 }
543}
544
545/*
546 * This is the global entry point. It examines the host for the optimal
547 * JRE to be used by scanning a set of registry entries. This set of entries
548 * is hardwired on Windows as "Software\JavaSoft\Java Runtime Environment"
549 * under the set of roots "{ HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }".
550 *
551 * This routine simply opens each of these registry directories before passing
552 * control onto ProcessDir().
553 */
554char *
555LocateJRE(manifest_info* info) {
556 HKEY key = NULL;
557 char *path;
558 int key_index;
559 HKEY root_keys[2] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE };
560
561 for (key_index = 0; key_index <= 1; key_index++) {
562 if (RegOpenKeyEx(root_keys[key_index], JRE_KEY, 0, KEY_READ, &key)
563 == ERROR_SUCCESS)
564 if ((path = ProcessDir(info, key)) != NULL) {
565 if (key != NULL)
566 RegCloseKey(key);
567 return (path);
568 }
569 if (key != NULL)
570 RegCloseKey(key);
571 }
572 return NULL;
573}
574
575/*
576 * Local helper routine to isolate a single token (option or argument)
577 * from the command line.
578 *
579 * This routine accepts a pointer to a character pointer. The first
580 * token (as defined by MSDN command-line argument syntax) is isolated
581 * from that string.
582 *
583 * Upon return, the input character pointer pointed to by the parameter s
584 * is updated to point to the remainding, unscanned, portion of the string,
585 * or to a null character if the entire string has been consummed.
586 *
587 * This function returns a pointer to a null-terminated string which
588 * contains the isolated first token, or to the null character if no
589 * token could be isolated.
590 *
591 * Note the side effect of modifying the input string s by the insertion
592 * of a null character, making it two strings.
593 *
594 * See "Parsing C Command-Line Arguments" in the MSDN Library for the
595 * parsing rule details. The rule summary from that specification is:
596 *
597 * * Arguments are delimited by white space, which is either a space or a tab.
598 *
599 * * A string surrounded by double quotation marks is interpreted as a single
600 * argument, regardless of white space contained within. A quoted string can
601 * be embedded in an argument. Note that the caret (^) is not recognized as
602 * an escape character or delimiter.
603 *
604 * * A double quotation mark preceded by a backslash, \", is interpreted as a
605 * literal double quotation mark (").
606 *
607 * * Backslashes are interpreted literally, unless they immediately precede a
608 * double quotation mark.
609 *
610 * * If an even number of backslashes is followed by a double quotation mark,
611 * then one backslash (\) is placed in the argv array for every pair of
612 * backslashes (\\), and the double quotation mark (") is interpreted as a
613 * string delimiter.
614 *
615 * * If an odd number of backslashes is followed by a double quotation mark,
616 * then one backslash (\) is placed in the argv array for every pair of
617 * backslashes (\\) and the double quotation mark is interpreted as an
618 * escape sequence by the remaining backslash, causing a literal double
619 * quotation mark (") to be placed in argv.
620 */
621static char*
622nextarg(char** s) {
623 char *p = *s;
624 char *head;
625 int slashes = 0;
626 int inquote = 0;
627
628 /*
629 * Strip leading whitespace, which MSDN defines as only space or tab.
630 * (Hence, no locale specific "isspace" here.)
631 */
632 while (*p != (char)0 && (*p == ' ' || *p == '\t'))
633 p++;
634 head = p; /* Save the start of the token to return */
635
636 /*
637 * Isolate a token from the command line.
638 */
639 while (*p != (char)0 && (inquote || !(*p == ' ' || *p == '\t'))) {
640 if (*p == '\\' && *(p+1) == '"' && slashes % 2 == 0)
641 p++;
642 else if (*p == '"')
643 inquote = !inquote;
644 slashes = (*p++ == '\\') ? slashes + 1 : 0;
645 }
646
647 /*
648 * If the token isolated isn't already terminated in a "char zero",
649 * then replace the whitespace character with one and move to the
650 * next character.
651 */
652 if (*p != (char)0)
653 *p++ = (char)0;
654
655 /*
656 * Update the parameter to point to the head of the remaining string
657 * reflecting the command line and return a pointer to the leading
658 * token which was isolated from the command line.
659 */
660 *s = p;
661 return (head);
662}
663
664/*
665 * Local helper routine to return a string equivalent to the input string
666 * s, but with quotes removed so the result is a string as would be found
667 * in argv[]. The returned string should be freed by a call to JLI_MemFree().
668 *
669 * The rules for quoting (and escaped quotes) are:
670 *
671 * 1 A double quotation mark preceded by a backslash, \", is interpreted as a
672 * literal double quotation mark (").
673 *
674 * 2 Backslashes are interpreted literally, unless they immediately precede a
675 * double quotation mark.
676 *
677 * 3 If an even number of backslashes is followed by a double quotation mark,
678 * then one backslash (\) is placed in the argv array for every pair of
679 * backslashes (\\), and the double quotation mark (") is interpreted as a
680 * string delimiter.
681 *
682 * 4 If an odd number of backslashes is followed by a double quotation mark,
683 * then one backslash (\) is placed in the argv array for every pair of
684 * backslashes (\\) and the double quotation mark is interpreted as an
685 * escape sequence by the remaining backslash, causing a literal double
686 * quotation mark (") to be placed in argv.
687 */
688static char*
689unquote(const char *s) {
690 const char *p = s; /* Pointer to the tail of the original string */
691 char *un = (char*)JLI_MemAlloc(JLI_StrLen(s) + 1); /* Ptr to unquoted string */
692 char *pun = un; /* Pointer to the tail of the unquoted string */
693
694 while (*p != '\0') {
695 if (*p == '"') {
696 p++;
697 } else if (*p == '\\') {
698 const char *q = p + JLI_StrSpn(p,"\\");
699 if (*q == '"')
700 do {
701 *pun++ = '\\';
702 p += 2;
703 } while (*p == '\\' && p < q);
704 else
705 while (p < q)
706 *pun++ = *p++;
707 } else {
708 *pun++ = *p++;
709 }
710 }
711 *pun = '\0';
712 return un;
713}
714
715/*
716 * Given a path to a jre to execute, this routine checks if this process
717 * is indeed that jre. If not, it exec's that jre.
718 *
719 * We want to actually check the paths rather than just the version string
720 * built into the executable, so that given version specification will yield
721 * the exact same Java environment, regardless of the version of the arbitrary
722 * launcher we start with.
723 */
724void
725ExecJRE(char *jre, char **argv) {
726 int len;
727 char path[MAXPATHLEN + 1];
728
729 const char *progname = GetProgramName();
730
731 /*
732 * Resolve the real path to the currently running launcher.
733 */
734 len = GetModuleFileName(NULL, path, MAXPATHLEN + 1);
735 if (len == 0 || len > MAXPATHLEN) {
736 ReportErrorMessageSys(JRE_ERROR9, progname);
737 exit(1);
738 }
739
740 JLI_TraceLauncher("ExecJRE: old: %s\n", path);
741 JLI_TraceLauncher("ExecJRE: new: %s\n", jre);
742
743 /*
744 * If the path to the selected JRE directory is a match to the initial
745 * portion of the path to the currently executing JRE, we have a winner!
746 * If so, just return.
747 */
748 if (JLI_StrNCaseCmp(jre, path, JLI_StrLen(jre)) == 0)
749 return; /* I am the droid you were looking for */
750
751 /*
752 * If this isn't the selected version, exec the selected version.
753 */
754 (void)JLI_StrCat(JLI_StrCat(JLI_StrCpy(path, jre), "\\bin\\"), progname);
755 (void)JLI_StrCat(path, ".exe");
756
757 /*
758 * Although Windows has an execv() entrypoint, it doesn't actually
759 * overlay a process: it can only create a new process and terminate
760 * the old process. Therefore, any processes waiting on the initial
761 * process wake up and they shouldn't. Hence, a chain of pseudo-zombie
762 * processes must be retained to maintain the proper wait semantics.
763 * Fortunately the image size of the launcher isn't too large at this
764 * time.
765 *
766 * If it weren't for this semantic flaw, the code below would be ...
767 *
768 * execv(path, argv);
769 * ReportErrorMessage("Error: Exec of %s failed\n", path);
770 * exit(1);
771 *
772 * The incorrect exec semantics could be addressed by:
773 *
774 * exit((int)spawnv(_P_WAIT, path, argv));
775 *
776 * Unfortunately, a bug in Windows spawn/exec impementation prevents
777 * this from completely working. All the Windows POSIX process creation
778 * interfaces are implemented as wrappers around the native Windows
779 * function CreateProcess(). CreateProcess() takes a single string
780 * to specify command line options and arguments, so the POSIX routine
781 * wrappers build a single string from the argv[] array and in the
782 * process, any quoting information is lost.
783 *
784 * The solution to this to get the original command line, to process it
785 * to remove the new multiple JRE options (if any) as was done for argv
786 * in the common SelectVersion() routine and finally to pass it directly
787 * to the native CreateProcess() Windows process control interface.
788 */
789 {
790 char *cmdline;
791 char *p;
792 char *np;
793 char *ocl;
794 char *ccl;
795 char *unquoted;
796 DWORD exitCode;
797 STARTUPINFO si;
798 PROCESS_INFORMATION pi;
799
800 /*
801 * The following code block gets and processes the original command
802 * line, replacing the argv[0] equivalent in the command line with
803 * the path to the new executable and removing the appropriate
804 * Multiple JRE support options. Note that similar logic exists
805 * in the platform independent SelectVersion routine, but is
806 * replicated here due to the syntax of CreateProcess().
807 *
808 * The magic "+ 4" characters added to the command line length are
809 * 2 possible quotes around the path (argv[0]), a space after the
810 * path and a terminating null character.
811 */
812 ocl = GetCommandLine();
813 np = ccl = JLI_StringDup(ocl);
814 p = nextarg(&np); /* Discard argv[0] */
815 cmdline = (char *)JLI_MemAlloc(JLI_StrLen(path) + JLI_StrLen(np) + 4);
816 if (JLI_StrChr(path, (int)' ') == NULL && JLI_StrChr(path, (int)'\t') == NULL)
817 cmdline = JLI_StrCpy(cmdline, path);
818 else
819 cmdline = JLI_StrCat(JLI_StrCat(JLI_StrCpy(cmdline, "\""), path), "\"");
820
821 while (*np != (char)0) { /* While more command-line */
822 p = nextarg(&np);
823 if (*p != (char)0) { /* If a token was isolated */
824 unquoted = unquote(p);
825 if (*unquoted == '-') { /* Looks like an option */
826 if (JLI_StrCmp(unquoted, "-classpath") == 0 ||
827 JLI_StrCmp(unquoted, "-cp") == 0) { /* Unique cp syntax */
828 cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
829 p = nextarg(&np);
830 if (*p != (char)0) /* If a token was isolated */
831 cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
832 } else if (JLI_StrNCmp(unquoted, "-version:", 9) != 0 &&
833 JLI_StrCmp(unquoted, "-jre-restrict-search") != 0 &&
834 JLI_StrCmp(unquoted, "-no-jre-restrict-search") != 0) {
835 cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
836 }
837 } else { /* End of options */
838 cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
839 cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), np);
840 JLI_MemFree((void *)unquoted);
841 break;
842 }
843 JLI_MemFree((void *)unquoted);
844 }
845 }
846 JLI_MemFree((void *)ccl);
847
848 if (JLI_IsTraceLauncher()) {
849 np = ccl = JLI_StringDup(cmdline);
850 p = nextarg(&np);
851 printf("ReExec Command: %s (%s)\n", path, p);
852 printf("ReExec Args: %s\n", np);
853 JLI_MemFree((void *)ccl);
854 }
855 (void)fflush(stdout);
856 (void)fflush(stderr);
857
858 /*
859 * The following code is modeled after a model presented in the
860 * Microsoft Technical Article "Moving Unix Applications to
861 * Windows NT" (March 6, 1994) and "Creating Processes" on MSDN
862 * (Februrary 2005). It approximates UNIX spawn semantics with
863 * the parent waiting for termination of the child.
864 */
865 memset(&si, 0, sizeof(si));
866 si.cb =sizeof(STARTUPINFO);
867 memset(&pi, 0, sizeof(pi));
868
869 if (!CreateProcess((LPCTSTR)path, /* executable name */
870 (LPTSTR)cmdline, /* command line */
871 (LPSECURITY_ATTRIBUTES)NULL, /* process security attr. */
872 (LPSECURITY_ATTRIBUTES)NULL, /* thread security attr. */
873 (BOOL)TRUE, /* inherits system handles */
874 (DWORD)0, /* creation flags */
875 (LPVOID)NULL, /* environment block */
876 (LPCTSTR)NULL, /* current directory */
877 (LPSTARTUPINFO)&si, /* (in) startup information */
878 (LPPROCESS_INFORMATION)&pi)) { /* (out) process information */
879 ReportErrorMessageSys(SYS_ERROR1, path);
880 exit(1);
881 }
882
883 if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_FAILED) {
884 if (GetExitCodeProcess(pi.hProcess, &exitCode) == FALSE)
885 exitCode = 1;
886 } else {
887 ReportErrorMessage(SYS_ERROR2);
888 exitCode = 1;
889 }
890
891 CloseHandle(pi.hThread);
892 CloseHandle(pi.hProcess);
893
894 exit(exitCode);
895 }
896
897}
898
899/*
900 * Wrapper for platform dependent unsetenv function.
901 */
902int
903UnsetEnv(char *name)
904{
905 int ret;
906 char *buf = JLI_MemAlloc(JLI_StrLen(name) + 2);
907 buf = JLI_StrCat(JLI_StrCpy(buf, name), "=");
908 ret = _putenv(buf);
909 JLI_MemFree(buf);
910 return (ret);
911}
912
913/* --- Splash Screen shared library support --- */
914
915static const char* SPLASHSCREEN_SO = "\\bin\\splashscreen.dll";
916
917static HMODULE hSplashLib = NULL;
918
919void* SplashProcAddress(const char* name) {
920 char libraryPath[MAXPATHLEN]; /* some extra space for JLI_StrCat'ing SPLASHSCREEN_SO */
921
922 if (!GetJREPath(libraryPath, MAXPATHLEN)) {
923 return NULL;
924 }
925 if (JLI_StrLen(libraryPath)+JLI_StrLen(SPLASHSCREEN_SO) >= MAXPATHLEN) {
926 return NULL;
927 }
928 JLI_StrCat(libraryPath, SPLASHSCREEN_SO);
929
930 if (!hSplashLib) {
931 hSplashLib = LoadLibrary(libraryPath);
932 }
933 if (hSplashLib) {
934 return GetProcAddress(hSplashLib, name);
935 } else {
936 return NULL;
937 }
938}
939
940void SplashFreeLibrary() {
941 if (hSplashLib) {
942 FreeLibrary(hSplashLib);
943 hSplashLib = NULL;
944 }
945}
946
947const char *
948jlong_format_specifier() {
949 return "%I64d";
950}
951
952/*
953 * Block current thread and continue execution in a new thread
954 */
955int
956ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void * args) {
957 int rslt = 0;
958 unsigned thread_id;
959
960#ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
961#define STACK_SIZE_PARAM_IS_A_RESERVATION (0x10000)
962#endif
963
964 /*
965 * STACK_SIZE_PARAM_IS_A_RESERVATION is what we want, but it's not
966 * supported on older version of Windows. Try first with the flag; and
967 * if that fails try again without the flag. See MSDN document or HotSpot
968 * source (os_win32.cpp) for details.
969 */
970 HANDLE thread_handle =
971 (HANDLE)_beginthreadex(NULL,
972 (unsigned)stack_size,
973 continuation,
974 args,
975 STACK_SIZE_PARAM_IS_A_RESERVATION,
976 &thread_id);
977 if (thread_handle == NULL) {
978 thread_handle =
979 (HANDLE)_beginthreadex(NULL,
980 (unsigned)stack_size,
981 continuation,
982 args,
983 0,
984 &thread_id);
985 }
986 if (thread_handle) {
987 WaitForSingleObject(thread_handle, INFINITE);
988 GetExitCodeThread(thread_handle, &rslt);
989 CloseHandle(thread_handle);
990 } else {
991 rslt = continuation(args);
992 }
993 return rslt;
994}
995
996/* Linux only, empty on windows. */
997void SetJavaLauncherPlatformProps() {}
ksrini52cded22008-03-06 07:51:28 -0800998
999void
1000InitLauncher(boolean javaw)
1001{
1002 INITCOMMONCONTROLSEX icx;
1003
1004 /*
1005 * Required for javaw mode MessageBox output as well as for
1006 * HotSpot -XX:+ShowMessageBoxOnError in java mode, an empty
1007 * flag field is sufficient to perform the basic UI initialization.
1008 */
1009 memset(&icx, 0, sizeof(INITCOMMONCONTROLSEX));
1010 icx.dwSize = sizeof(INITCOMMONCONTROLSEX);
1011 InitCommonControlsEx(&icx);
1012 _isjavaw = javaw;
1013 JLI_SetTraceLauncher();
1014}