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