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