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