blob: abd887c94d56a7fe235643225122dfadd483539c [file] [log] [blame]
duke6e45e102007-12-01 00:00:00 +00001/*
ksrinie3ec45d2010-07-09 11:04:34 -07002 * Copyright (c) 1997, 2010, Oracle and/or its affiliates. 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
ohair2283b9d2010-05-25 15:58:33 -07007 * published by the Free Software Foundation. Oracle designates this
duke6e45e102007-12-01 00:00:00 +00008 * particular file as subject to the "Classpath" exception as provided
ohair2283b9d2010-05-25 15:58:33 -07009 * by Oracle in the LICENSE file that accompanied this code.
duke6e45e102007-12-01 00:00:00 +000010 *
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 *
ohair2283b9d2010-05-25 15:58:33 -070021 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
duke6e45e102007-12-01 00:00:00 +000024 */
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
ksrinie3ec45d2010-07-09 11:04:34 -070083CreateExecutionEnvironment(int *pargc, char ***pargv,
84 char *jrepath, jint so_jrepath,
85 char *jvmpath, jint so_jvmpath) {
duke6e45e102007-12-01 00:00:00 +000086 char * jvmtype;
87 int i = 0;
duke6e45e102007-12-01 00:00:00 +000088 int running = CURRENT_DATA_MODEL;
89
90 int wanted = running;
91
ksrinie3ec45d2010-07-09 11:04:34 -070092 char** argv = *pargv;
93 for (i = 0; i < *pargc ; i++) {
94 if (JLI_StrCmp(argv[i], "-J-d64") == 0 || JLI_StrCmp(argv[i], "-d64") == 0) {
duke6e45e102007-12-01 00:00:00 +000095 wanted = 64;
96 continue;
97 }
ksrinie3ec45d2010-07-09 11:04:34 -070098 if (JLI_StrCmp(argv[i], "-J-d32") == 0 || JLI_StrCmp(argv[i], "-d32") == 0) {
duke6e45e102007-12-01 00:00:00 +000099 wanted = 32;
100 continue;
101 }
102 }
103 if (running != wanted) {
ksrini0e817162008-08-26 10:21:20 -0700104 JLI_ReportErrorMessage(JRE_ERROR2, wanted);
duke6e45e102007-12-01 00:00:00 +0000105 exit(1);
106 }
107
108 /* Find out where the JRE is that we will be using. */
109 if (!GetJREPath(jrepath, so_jrepath)) {
ksrini0e817162008-08-26 10:21:20 -0700110 JLI_ReportErrorMessage(JRE_ERROR1);
duke6e45e102007-12-01 00:00:00 +0000111 exit(2);
112 }
113
ksrini9fb23882010-09-03 07:59:21 -0700114 /* Do this before we read jvm.cfg and after jrepath is initialized */
115 EnsureJreInstallation(jrepath);
116
duke6e45e102007-12-01 00:00:00 +0000117 /* 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 }
ksrinie3ec45d2010-07-09 11:04:34 -0700122
123 jvmtype = CheckJvmType(pargc, pargv, JNI_FALSE);
124 if (JLI_StrCmp(jvmtype, "ERROR") == 0) {
125 JLI_ReportErrorMessage(CFG_ERROR9);
126 exit(4);
127 }
duke6e45e102007-12-01 00:00:00 +0000128
129 jvmpath[0] = '\0';
130 if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath)) {
ksrini0e817162008-08-26 10:21:20 -0700131 JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath);
duke6e45e102007-12-01 00:00:00 +0000132 exit(4);
133 }
134 /* If we got here, jvmpath has been correctly initialized. */
duke6e45e102007-12-01 00:00:00 +0000135}
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
ksrinie3ec45d2010-07-09 11:04:34 -0700206 /* Make sure the jrepath contains something */
207 if (jrepath[0] == NULL) {
208 return;
209 }
herrick43e2a0c2009-06-12 14:56:32 -0400210 /* 32 bit windows only please */
ksrinie3ec45d2010-07-09 11:04:34 -0700211 if (JLI_StrCmp(GetArch(), "i386") != 0 ) {
herrick43e2a0c2009-06-12 14:56:32 -0400212 return;
213 }
214 /* Does our bundle directory exist ? */
ksrinie3ec45d2010-07-09 11:04:34 -0700215 JLI_Snprintf(tmpbuf, sizeof(tmpbuf), "%s\\lib\\bundles", jrepath);
ksrini9fb23882010-09-03 07:59:21 -0700216 JLI_TraceLauncher("EnsureJreInstallation: %s\n", tmpbuf);
herrick43e2a0c2009-06-12 14:56:32 -0400217 if (stat(tmpbuf, &s) != 0) {
218 return;
219 }
220 /* Does our jkernel dll exist ? */
ksrinie3ec45d2010-07-09 11:04:34 -0700221 JLI_Snprintf(tmpbuf, sizeof(tmpbuf), "%s\\bin\\jkernel.dll", jrepath);
herrick43e2a0c2009-06-12 14:56:32 -0400222 if (stat(tmpbuf, &s) != 0) {
223 return;
224 }
225 /* The Microsoft C Runtime Library needs to be loaded first. */
226 if (!LoadMSVCRT()) {
227 return;
228 }
229 /* Load the jkernel.dll */
230 if ((handle = LoadLibrary(tmpbuf)) == 0) {
231 return;
232 }
233 /* Get the function address */
234 PreJVMStart = (PREJVMSTART)GetProcAddress(handle, "preJVMStart");
235 if (PreJVMStart == NULL) {
236 FreeLibrary(handle);
237 return;
238 }
239 PreJVMStart();
240 FreeLibrary(handle);
241 return;
242}
243
duke6e45e102007-12-01 00:00:00 +0000244/*
245 * Find path to JRE based on .exe's location or registry settings.
246 */
247jboolean
248GetJREPath(char *path, jint pathsize)
249{
250 char javadll[MAXPATHLEN];
251 struct stat s;
252
253 if (GetApplicationHome(path, pathsize)) {
254 /* Is JRE co-located with the application? */
ksrinie3ec45d2010-07-09 11:04:34 -0700255 JLI_Snprintf(javadll, sizeof(javadll), "%s\\bin\\" JAVA_DLL, path);
duke6e45e102007-12-01 00:00:00 +0000256 if (stat(javadll, &s) == 0) {
ksrinie3ec45d2010-07-09 11:04:34 -0700257 JLI_TraceLauncher("JRE path is %s\n", path);
258 return JNI_TRUE;
duke6e45e102007-12-01 00:00:00 +0000259 }
260
261 /* Does this app ship a private JRE in <apphome>\jre directory? */
ksrinie3ec45d2010-07-09 11:04:34 -0700262 JLI_Snprintf(javadll, sizeof (javadll), "%s\\jre\\bin\\" JAVA_DLL, path);
duke6e45e102007-12-01 00:00:00 +0000263 if (stat(javadll, &s) == 0) {
264 JLI_StrCat(path, "\\jre");
ksrinie3ec45d2010-07-09 11:04:34 -0700265 JLI_TraceLauncher("JRE path is %s\n", path);
266 return JNI_TRUE;
duke6e45e102007-12-01 00:00:00 +0000267 }
268 }
269
270 /* Look for a public JRE on this machine. */
271 if (GetPublicJREHome(path, pathsize)) {
ksrinie3ec45d2010-07-09 11:04:34 -0700272 JLI_TraceLauncher("JRE path is %s\n", path);
273 return JNI_TRUE;
duke6e45e102007-12-01 00:00:00 +0000274 }
275
ksrini0e817162008-08-26 10:21:20 -0700276 JLI_ReportErrorMessage(JRE_ERROR8 JAVA_DLL);
duke6e45e102007-12-01 00:00:00 +0000277 return JNI_FALSE;
278
duke6e45e102007-12-01 00:00:00 +0000279}
280
281/*
282 * Given a JRE location and a JVM type, construct what the name the
283 * JVM shared library will be. Return true, if such a library
284 * exists, false otherwise.
285 */
286static jboolean
287GetJVMPath(const char *jrepath, const char *jvmtype,
288 char *jvmpath, jint jvmpathsize)
289{
290 struct stat s;
291 if (JLI_StrChr(jvmtype, '/') || JLI_StrChr(jvmtype, '\\')) {
ksrinie3ec45d2010-07-09 11:04:34 -0700292 JLI_Snprintf(jvmpath, jvmpathsize, "%s\\" JVM_DLL, jvmtype);
duke6e45e102007-12-01 00:00:00 +0000293 } else {
ksrinie3ec45d2010-07-09 11:04:34 -0700294 JLI_Snprintf(jvmpath, jvmpathsize, "%s\\bin\\%s\\" JVM_DLL, jrepath, jvmtype);
duke6e45e102007-12-01 00:00:00 +0000295 }
296 if (stat(jvmpath, &s) == 0) {
297 return JNI_TRUE;
298 } else {
299 return JNI_FALSE;
300 }
301}
302
303/*
304 * Load a jvm from "jvmpath" and initialize the invocation functions.
305 */
306jboolean
307LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)
308{
309 HINSTANCE handle;
duke6e45e102007-12-01 00:00:00 +0000310
311 JLI_TraceLauncher("JVM path is %s\n", jvmpath);
312
313 /*
314 * The Microsoft C Runtime Library needs to be loaded first. A copy is
315 * assumed to be present in the "JRE path" directory. If it is not found
316 * there (or "JRE path" fails to resolve), skip the explicit load and let
317 * nature take its course, which is likely to be a failure to execute.
tbellfc2a6fe2009-01-14 21:35:03 -0800318 *
duke6e45e102007-12-01 00:00:00 +0000319 */
herrick43e2a0c2009-06-12 14:56:32 -0400320 LoadMSVCRT();
duke6e45e102007-12-01 00:00:00 +0000321
322 /* Load the Java VM DLL */
323 if ((handle = LoadLibrary(jvmpath)) == 0) {
ksrini0e817162008-08-26 10:21:20 -0700324 JLI_ReportErrorMessage(DLL_ERROR4, (char *)jvmpath);
duke6e45e102007-12-01 00:00:00 +0000325 return JNI_FALSE;
326 }
327
328 /* Now get the function addresses */
329 ifn->CreateJavaVM =
330 (void *)GetProcAddress(handle, "JNI_CreateJavaVM");
331 ifn->GetDefaultJavaVMInitArgs =
332 (void *)GetProcAddress(handle, "JNI_GetDefaultJavaVMInitArgs");
333 if (ifn->CreateJavaVM == 0 || ifn->GetDefaultJavaVMInitArgs == 0) {
ksrini0e817162008-08-26 10:21:20 -0700334 JLI_ReportErrorMessage(JNI_ERROR1, (char *)jvmpath);
duke6e45e102007-12-01 00:00:00 +0000335 return JNI_FALSE;
336 }
337
338 return JNI_TRUE;
339}
340
341/*
342 * If app is "c:\foo\bin\javac", then put "c:\foo" into buf.
343 */
344jboolean
345GetApplicationHome(char *buf, jint bufsize)
346{
347 char *cp;
348 GetModuleFileName(0, buf, bufsize);
349 *JLI_StrRChr(buf, '\\') = '\0'; /* remove .exe file name */
350 if ((cp = JLI_StrRChr(buf, '\\')) == 0) {
351 /* This happens if the application is in a drive root, and
352 * there is no bin directory. */
353 buf[0] = '\0';
354 return JNI_FALSE;
355 }
356 *cp = '\0'; /* remove the bin\ part */
357 return JNI_TRUE;
358}
359
360/*
361 * Helpers to look in the registry for a public JRE.
362 */
363 /* Same for 1.5.0, 1.5.1, 1.5.2 etc. */
364#define JRE_KEY "Software\\JavaSoft\\Java Runtime Environment"
365
366static jboolean
367GetStringFromRegistry(HKEY key, const char *name, char *buf, jint bufsize)
368{
369 DWORD type, size;
370
371 if (RegQueryValueEx(key, name, 0, &type, 0, &size) == 0
372 && type == REG_SZ
373 && (size < (unsigned int)bufsize)) {
374 if (RegQueryValueEx(key, name, 0, 0, buf, &size) == 0) {
375 return JNI_TRUE;
376 }
377 }
378 return JNI_FALSE;
379}
380
381static jboolean
382GetPublicJREHome(char *buf, jint bufsize)
383{
384 HKEY key, subkey;
385 char version[MAXPATHLEN];
386
387 /*
388 * Note: There is a very similar implementation of the following
389 * registry reading code in the Windows java control panel (javacp.cpl).
390 * If there are bugs here, a similar bug probably exists there. Hence,
391 * changes here require inspection there.
392 */
393
394 /* Find the current version of the JRE */
395 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, JRE_KEY, 0, KEY_READ, &key) != 0) {
ksrini0e817162008-08-26 10:21:20 -0700396 JLI_ReportErrorMessage(REG_ERROR1, JRE_KEY);
duke6e45e102007-12-01 00:00:00 +0000397 return JNI_FALSE;
398 }
399
400 if (!GetStringFromRegistry(key, "CurrentVersion",
401 version, sizeof(version))) {
ksrini0e817162008-08-26 10:21:20 -0700402 JLI_ReportErrorMessage(REG_ERROR2, JRE_KEY);
duke6e45e102007-12-01 00:00:00 +0000403 RegCloseKey(key);
404 return JNI_FALSE;
405 }
406
407 if (JLI_StrCmp(version, GetDotVersion()) != 0) {
ksrini0e817162008-08-26 10:21:20 -0700408 JLI_ReportErrorMessage(REG_ERROR3, JRE_KEY, version, GetDotVersion()
duke6e45e102007-12-01 00:00:00 +0000409 );
410 RegCloseKey(key);
411 return JNI_FALSE;
412 }
413
414 /* Find directory where the current version is installed. */
415 if (RegOpenKeyEx(key, version, 0, KEY_READ, &subkey) != 0) {
ksrini0e817162008-08-26 10:21:20 -0700416 JLI_ReportErrorMessage(REG_ERROR1, JRE_KEY, version);
duke6e45e102007-12-01 00:00:00 +0000417 RegCloseKey(key);
418 return JNI_FALSE;
419 }
420
421 if (!GetStringFromRegistry(subkey, "JavaHome", buf, bufsize)) {
ksrini0e817162008-08-26 10:21:20 -0700422 JLI_ReportErrorMessage(REG_ERROR4, JRE_KEY, version);
duke6e45e102007-12-01 00:00:00 +0000423 RegCloseKey(key);
424 RegCloseKey(subkey);
425 return JNI_FALSE;
426 }
427
428 if (JLI_IsTraceLauncher()) {
429 char micro[MAXPATHLEN];
430 if (!GetStringFromRegistry(subkey, "MicroVersion", micro,
431 sizeof(micro))) {
432 printf("Warning: Can't read MicroVersion\n");
433 micro[0] = '\0';
434 }
435 printf("Version major.minor.micro = %s.%s\n", version, micro);
436 }
437
438 RegCloseKey(key);
439 RegCloseKey(subkey);
440 return JNI_TRUE;
441}
442
443/*
444 * Support for doing cheap, accurate interval timing.
445 */
446static jboolean counterAvailable = JNI_FALSE;
447static jboolean counterInitialized = JNI_FALSE;
448static LARGE_INTEGER counterFrequency;
449
450jlong CounterGet()
451{
452 LARGE_INTEGER count;
453
454 if (!counterInitialized) {
455 counterAvailable = QueryPerformanceFrequency(&counterFrequency);
456 counterInitialized = JNI_TRUE;
457 }
458 if (!counterAvailable) {
459 return 0;
460 }
461 QueryPerformanceCounter(&count);
462 return (jlong)(count.QuadPart);
463}
464
465jlong Counter2Micros(jlong counts)
466{
467 if (!counterAvailable || !counterInitialized) {
468 return 0;
469 }
470 return (counts * 1000 * 1000)/counterFrequency.QuadPart;
471}
472
473void
ksrini0e817162008-08-26 10:21:20 -0700474JLI_ReportErrorMessage(const char* fmt, ...) {
duke6e45e102007-12-01 00:00:00 +0000475 va_list vl;
476 va_start(vl,fmt);
477
478 if (IsJavaw()) {
479 char *message;
480
481 /* get the length of the string we need */
482 int n = _vscprintf(fmt, vl);
483
484 message = (char *)JLI_MemAlloc(n + 1);
485 _vsnprintf(message, n, fmt, vl);
486 message[n]='\0';
487 MessageBox(NULL, message, "Java Virtual Machine Launcher",
488 (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
489 JLI_MemFree(message);
490 } else {
491 vfprintf(stderr, fmt, vl);
492 fprintf(stderr, "\n");
493 }
494 va_end(vl);
495}
496
497/*
ksrini0e817162008-08-26 10:21:20 -0700498 * Just like JLI_ReportErrorMessage, except that it concatenates the system
duke6e45e102007-12-01 00:00:00 +0000499 * error message if any, its upto the calling routine to correctly
500 * format the separation of the messages.
501 */
502void
ksrini0e817162008-08-26 10:21:20 -0700503JLI_ReportErrorMessageSys(const char *fmt, ...)
duke6e45e102007-12-01 00:00:00 +0000504{
505 va_list vl;
506
507 int save_errno = errno;
508 DWORD errval;
509 jboolean freeit = JNI_FALSE;
510 char *errtext = NULL;
511
512 va_start(vl, fmt);
513
514 if ((errval = GetLastError()) != 0) { /* Platform SDK / DOS Error */
515 int n = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|
516 FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_ALLOCATE_BUFFER,
517 NULL, errval, 0, (LPTSTR)&errtext, 0, NULL);
518 if (errtext == NULL || n == 0) { /* Paranoia check */
519 errtext = "";
520 n = 0;
521 } else {
522 freeit = JNI_TRUE;
523 if (n > 2) { /* Drop final CR, LF */
524 if (errtext[n - 1] == '\n') n--;
525 if (errtext[n - 1] == '\r') n--;
526 errtext[n] = '\0';
527 }
528 }
529 } else { /* C runtime error that has no corresponding DOS error code */
530 errtext = strerror(save_errno);
531 }
532
533 if (IsJavaw()) {
534 char *message;
535 int mlen;
536 /* get the length of the string we need */
537 int len = mlen = _vscprintf(fmt, vl) + 1;
538 if (freeit) {
539 mlen += JLI_StrLen(errtext);
540 }
541
542 message = (char *)JLI_MemAlloc(mlen);
543 _vsnprintf(message, len, fmt, vl);
544 message[len]='\0';
545
546 if (freeit) {
547 JLI_StrCat(message, errtext);
548 }
549
550 MessageBox(NULL, message, "Java Virtual Machine Launcher",
551 (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
552
553 JLI_MemFree(message);
554 } else {
555 vfprintf(stderr, fmt, vl);
556 if (freeit) {
557 fprintf(stderr, "%s", errtext);
558 }
559 }
560 if (freeit) {
561 (void)LocalFree((HLOCAL)errtext);
562 }
563 va_end(vl);
564}
565
ksrini0e817162008-08-26 10:21:20 -0700566void JLI_ReportExceptionDescription(JNIEnv * env) {
duke6e45e102007-12-01 00:00:00 +0000567 if (IsJavaw()) {
568 /*
569 * This code should be replaced by code which opens a window with
570 * the exception detail message, for now atleast put a dialog up.
571 */
572 MessageBox(NULL, "A Java Exception has occurred.", "Java Virtual Machine Launcher",
573 (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
574 } else {
575 (*env)->ExceptionDescribe(env);
576 }
577}
578
579jboolean
580ServerClassMachine() {
581 return (GetErgoPolicy() == ALWAYS_SERVER_CLASS) ? JNI_TRUE : JNI_FALSE;
582}
583
584/*
585 * Determine if there is an acceptable JRE in the registry directory top_key.
586 * Upon locating the "best" one, return a fully qualified path to it.
587 * "Best" is defined as the most advanced JRE meeting the constraints
588 * contained in the manifest_info. If no JRE in this directory meets the
589 * constraints, return NULL.
590 *
591 * It doesn't matter if we get an error reading the registry, or we just
592 * don't find anything interesting in the directory. We just return NULL
593 * in either case.
594 */
595static char *
596ProcessDir(manifest_info* info, HKEY top_key) {
597 DWORD index = 0;
598 HKEY ver_key;
599 char name[MAXNAMELEN];
600 int len;
601 char *best = NULL;
602
603 /*
604 * Enumerate "<top_key>/SOFTWARE/JavaSoft/Java Runtime Environment"
605 * searching for the best available version.
606 */
607 while (RegEnumKey(top_key, index, name, MAXNAMELEN) == ERROR_SUCCESS) {
608 index++;
609 if (JLI_AcceptableRelease(name, info->jre_version))
610 if ((best == NULL) || (JLI_ExactVersionId(name, best) > 0)) {
611 if (best != NULL)
612 JLI_MemFree(best);
613 best = JLI_StringDup(name);
614 }
615 }
616
617 /*
618 * Extract "JavaHome" from the "best" registry directory and return
619 * that path. If no appropriate version was located, or there is an
620 * error in extracting the "JavaHome" string, return null.
621 */
622 if (best == NULL)
623 return (NULL);
624 else {
625 if (RegOpenKeyEx(top_key, best, 0, KEY_READ, &ver_key)
626 != ERROR_SUCCESS) {
627 JLI_MemFree(best);
628 if (ver_key != NULL)
629 RegCloseKey(ver_key);
630 return (NULL);
631 }
632 JLI_MemFree(best);
633 len = MAXNAMELEN;
634 if (RegQueryValueEx(ver_key, "JavaHome", NULL, NULL, (LPBYTE)name, &len)
635 != ERROR_SUCCESS) {
636 if (ver_key != NULL)
637 RegCloseKey(ver_key);
638 return (NULL);
639 }
640 if (ver_key != NULL)
641 RegCloseKey(ver_key);
642 return (JLI_StringDup(name));
643 }
644}
645
646/*
647 * This is the global entry point. It examines the host for the optimal
648 * JRE to be used by scanning a set of registry entries. This set of entries
649 * is hardwired on Windows as "Software\JavaSoft\Java Runtime Environment"
650 * under the set of roots "{ HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }".
651 *
652 * This routine simply opens each of these registry directories before passing
653 * control onto ProcessDir().
654 */
655char *
656LocateJRE(manifest_info* info) {
657 HKEY key = NULL;
658 char *path;
659 int key_index;
660 HKEY root_keys[2] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE };
661
662 for (key_index = 0; key_index <= 1; key_index++) {
663 if (RegOpenKeyEx(root_keys[key_index], JRE_KEY, 0, KEY_READ, &key)
664 == ERROR_SUCCESS)
665 if ((path = ProcessDir(info, key)) != NULL) {
666 if (key != NULL)
667 RegCloseKey(key);
668 return (path);
669 }
670 if (key != NULL)
671 RegCloseKey(key);
672 }
673 return NULL;
674}
675
676/*
677 * Local helper routine to isolate a single token (option or argument)
678 * from the command line.
679 *
680 * This routine accepts a pointer to a character pointer. The first
681 * token (as defined by MSDN command-line argument syntax) is isolated
682 * from that string.
683 *
684 * Upon return, the input character pointer pointed to by the parameter s
685 * is updated to point to the remainding, unscanned, portion of the string,
686 * or to a null character if the entire string has been consummed.
687 *
688 * This function returns a pointer to a null-terminated string which
689 * contains the isolated first token, or to the null character if no
690 * token could be isolated.
691 *
692 * Note the side effect of modifying the input string s by the insertion
693 * of a null character, making it two strings.
694 *
695 * See "Parsing C Command-Line Arguments" in the MSDN Library for the
696 * parsing rule details. The rule summary from that specification is:
697 *
698 * * Arguments are delimited by white space, which is either a space or a tab.
699 *
700 * * A string surrounded by double quotation marks is interpreted as a single
701 * argument, regardless of white space contained within. A quoted string can
702 * be embedded in an argument. Note that the caret (^) is not recognized as
703 * an escape character or delimiter.
704 *
705 * * A double quotation mark preceded by a backslash, \", is interpreted as a
706 * literal double quotation mark (").
707 *
708 * * Backslashes are interpreted literally, unless they immediately precede a
709 * double quotation mark.
710 *
711 * * If an even number of backslashes is followed by a double quotation mark,
712 * then one backslash (\) is placed in the argv array for every pair of
713 * backslashes (\\), and the double quotation mark (") is interpreted as a
714 * string delimiter.
715 *
716 * * If an odd number of backslashes is followed by a double quotation mark,
717 * then one backslash (\) is placed in the argv array for every pair of
718 * backslashes (\\) and the double quotation mark is interpreted as an
719 * escape sequence by the remaining backslash, causing a literal double
720 * quotation mark (") to be placed in argv.
721 */
722static char*
723nextarg(char** s) {
724 char *p = *s;
725 char *head;
726 int slashes = 0;
727 int inquote = 0;
728
729 /*
730 * Strip leading whitespace, which MSDN defines as only space or tab.
731 * (Hence, no locale specific "isspace" here.)
732 */
733 while (*p != (char)0 && (*p == ' ' || *p == '\t'))
734 p++;
735 head = p; /* Save the start of the token to return */
736
737 /*
738 * Isolate a token from the command line.
739 */
740 while (*p != (char)0 && (inquote || !(*p == ' ' || *p == '\t'))) {
741 if (*p == '\\' && *(p+1) == '"' && slashes % 2 == 0)
742 p++;
743 else if (*p == '"')
744 inquote = !inquote;
745 slashes = (*p++ == '\\') ? slashes + 1 : 0;
746 }
747
748 /*
749 * If the token isolated isn't already terminated in a "char zero",
750 * then replace the whitespace character with one and move to the
751 * next character.
752 */
753 if (*p != (char)0)
754 *p++ = (char)0;
755
756 /*
757 * Update the parameter to point to the head of the remaining string
758 * reflecting the command line and return a pointer to the leading
759 * token which was isolated from the command line.
760 */
761 *s = p;
762 return (head);
763}
764
765/*
766 * Local helper routine to return a string equivalent to the input string
767 * s, but with quotes removed so the result is a string as would be found
768 * in argv[]. The returned string should be freed by a call to JLI_MemFree().
769 *
770 * The rules for quoting (and escaped quotes) are:
771 *
772 * 1 A double quotation mark preceded by a backslash, \", is interpreted as a
773 * literal double quotation mark (").
774 *
775 * 2 Backslashes are interpreted literally, unless they immediately precede a
776 * double quotation mark.
777 *
778 * 3 If an even number of backslashes is followed by a double quotation mark,
779 * then one backslash (\) is placed in the argv array for every pair of
780 * backslashes (\\), and the double quotation mark (") is interpreted as a
781 * string delimiter.
782 *
783 * 4 If an odd number of backslashes is followed by a double quotation mark,
784 * then one backslash (\) is placed in the argv array for every pair of
785 * backslashes (\\) and the double quotation mark is interpreted as an
786 * escape sequence by the remaining backslash, causing a literal double
787 * quotation mark (") to be placed in argv.
788 */
789static char*
790unquote(const char *s) {
791 const char *p = s; /* Pointer to the tail of the original string */
792 char *un = (char*)JLI_MemAlloc(JLI_StrLen(s) + 1); /* Ptr to unquoted string */
793 char *pun = un; /* Pointer to the tail of the unquoted string */
794
795 while (*p != '\0') {
796 if (*p == '"') {
797 p++;
798 } else if (*p == '\\') {
799 const char *q = p + JLI_StrSpn(p,"\\");
800 if (*q == '"')
801 do {
802 *pun++ = '\\';
803 p += 2;
804 } while (*p == '\\' && p < q);
805 else
806 while (p < q)
807 *pun++ = *p++;
808 } else {
809 *pun++ = *p++;
810 }
811 }
812 *pun = '\0';
813 return un;
814}
815
816/*
817 * Given a path to a jre to execute, this routine checks if this process
818 * is indeed that jre. If not, it exec's that jre.
819 *
820 * We want to actually check the paths rather than just the version string
821 * built into the executable, so that given version specification will yield
822 * the exact same Java environment, regardless of the version of the arbitrary
823 * launcher we start with.
824 */
825void
826ExecJRE(char *jre, char **argv) {
827 int len;
828 char path[MAXPATHLEN + 1];
829
830 const char *progname = GetProgramName();
831
832 /*
833 * Resolve the real path to the currently running launcher.
834 */
835 len = GetModuleFileName(NULL, path, MAXPATHLEN + 1);
836 if (len == 0 || len > MAXPATHLEN) {
ksrini0e817162008-08-26 10:21:20 -0700837 JLI_ReportErrorMessageSys(JRE_ERROR9, progname);
duke6e45e102007-12-01 00:00:00 +0000838 exit(1);
839 }
840
841 JLI_TraceLauncher("ExecJRE: old: %s\n", path);
842 JLI_TraceLauncher("ExecJRE: new: %s\n", jre);
843
844 /*
845 * If the path to the selected JRE directory is a match to the initial
846 * portion of the path to the currently executing JRE, we have a winner!
847 * If so, just return.
848 */
849 if (JLI_StrNCaseCmp(jre, path, JLI_StrLen(jre)) == 0)
850 return; /* I am the droid you were looking for */
851
852 /*
853 * If this isn't the selected version, exec the selected version.
854 */
855 (void)JLI_StrCat(JLI_StrCat(JLI_StrCpy(path, jre), "\\bin\\"), progname);
856 (void)JLI_StrCat(path, ".exe");
857
858 /*
859 * Although Windows has an execv() entrypoint, it doesn't actually
860 * overlay a process: it can only create a new process and terminate
861 * the old process. Therefore, any processes waiting on the initial
862 * process wake up and they shouldn't. Hence, a chain of pseudo-zombie
863 * processes must be retained to maintain the proper wait semantics.
864 * Fortunately the image size of the launcher isn't too large at this
865 * time.
866 *
867 * If it weren't for this semantic flaw, the code below would be ...
868 *
869 * execv(path, argv);
ksrini0e817162008-08-26 10:21:20 -0700870 * JLI_ReportErrorMessage("Error: Exec of %s failed\n", path);
duke6e45e102007-12-01 00:00:00 +0000871 * exit(1);
872 *
873 * The incorrect exec semantics could be addressed by:
874 *
875 * exit((int)spawnv(_P_WAIT, path, argv));
876 *
877 * Unfortunately, a bug in Windows spawn/exec impementation prevents
878 * this from completely working. All the Windows POSIX process creation
879 * interfaces are implemented as wrappers around the native Windows
880 * function CreateProcess(). CreateProcess() takes a single string
881 * to specify command line options and arguments, so the POSIX routine
882 * wrappers build a single string from the argv[] array and in the
883 * process, any quoting information is lost.
884 *
885 * The solution to this to get the original command line, to process it
886 * to remove the new multiple JRE options (if any) as was done for argv
887 * in the common SelectVersion() routine and finally to pass it directly
888 * to the native CreateProcess() Windows process control interface.
889 */
890 {
891 char *cmdline;
892 char *p;
893 char *np;
894 char *ocl;
895 char *ccl;
896 char *unquoted;
897 DWORD exitCode;
898 STARTUPINFO si;
899 PROCESS_INFORMATION pi;
900
901 /*
902 * The following code block gets and processes the original command
903 * line, replacing the argv[0] equivalent in the command line with
904 * the path to the new executable and removing the appropriate
905 * Multiple JRE support options. Note that similar logic exists
906 * in the platform independent SelectVersion routine, but is
907 * replicated here due to the syntax of CreateProcess().
908 *
909 * The magic "+ 4" characters added to the command line length are
910 * 2 possible quotes around the path (argv[0]), a space after the
911 * path and a terminating null character.
912 */
913 ocl = GetCommandLine();
914 np = ccl = JLI_StringDup(ocl);
915 p = nextarg(&np); /* Discard argv[0] */
916 cmdline = (char *)JLI_MemAlloc(JLI_StrLen(path) + JLI_StrLen(np) + 4);
917 if (JLI_StrChr(path, (int)' ') == NULL && JLI_StrChr(path, (int)'\t') == NULL)
918 cmdline = JLI_StrCpy(cmdline, path);
919 else
920 cmdline = JLI_StrCat(JLI_StrCat(JLI_StrCpy(cmdline, "\""), path), "\"");
921
922 while (*np != (char)0) { /* While more command-line */
923 p = nextarg(&np);
924 if (*p != (char)0) { /* If a token was isolated */
925 unquoted = unquote(p);
926 if (*unquoted == '-') { /* Looks like an option */
927 if (JLI_StrCmp(unquoted, "-classpath") == 0 ||
928 JLI_StrCmp(unquoted, "-cp") == 0) { /* Unique cp syntax */
929 cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
930 p = nextarg(&np);
931 if (*p != (char)0) /* If a token was isolated */
932 cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
933 } else if (JLI_StrNCmp(unquoted, "-version:", 9) != 0 &&
934 JLI_StrCmp(unquoted, "-jre-restrict-search") != 0 &&
935 JLI_StrCmp(unquoted, "-no-jre-restrict-search") != 0) {
936 cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
937 }
938 } else { /* End of options */
939 cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
940 cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), np);
941 JLI_MemFree((void *)unquoted);
942 break;
943 }
944 JLI_MemFree((void *)unquoted);
945 }
946 }
947 JLI_MemFree((void *)ccl);
948
949 if (JLI_IsTraceLauncher()) {
950 np = ccl = JLI_StringDup(cmdline);
951 p = nextarg(&np);
952 printf("ReExec Command: %s (%s)\n", path, p);
953 printf("ReExec Args: %s\n", np);
954 JLI_MemFree((void *)ccl);
955 }
956 (void)fflush(stdout);
957 (void)fflush(stderr);
958
959 /*
960 * The following code is modeled after a model presented in the
961 * Microsoft Technical Article "Moving Unix Applications to
962 * Windows NT" (March 6, 1994) and "Creating Processes" on MSDN
963 * (Februrary 2005). It approximates UNIX spawn semantics with
964 * the parent waiting for termination of the child.
965 */
966 memset(&si, 0, sizeof(si));
967 si.cb =sizeof(STARTUPINFO);
968 memset(&pi, 0, sizeof(pi));
969
970 if (!CreateProcess((LPCTSTR)path, /* executable name */
971 (LPTSTR)cmdline, /* command line */
972 (LPSECURITY_ATTRIBUTES)NULL, /* process security attr. */
973 (LPSECURITY_ATTRIBUTES)NULL, /* thread security attr. */
974 (BOOL)TRUE, /* inherits system handles */
975 (DWORD)0, /* creation flags */
976 (LPVOID)NULL, /* environment block */
977 (LPCTSTR)NULL, /* current directory */
978 (LPSTARTUPINFO)&si, /* (in) startup information */
979 (LPPROCESS_INFORMATION)&pi)) { /* (out) process information */
ksrini0e817162008-08-26 10:21:20 -0700980 JLI_ReportErrorMessageSys(SYS_ERROR1, path);
duke6e45e102007-12-01 00:00:00 +0000981 exit(1);
982 }
983
984 if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_FAILED) {
985 if (GetExitCodeProcess(pi.hProcess, &exitCode) == FALSE)
986 exitCode = 1;
987 } else {
ksrini0e817162008-08-26 10:21:20 -0700988 JLI_ReportErrorMessage(SYS_ERROR2);
duke6e45e102007-12-01 00:00:00 +0000989 exitCode = 1;
990 }
991
992 CloseHandle(pi.hThread);
993 CloseHandle(pi.hProcess);
994
995 exit(exitCode);
996 }
997
998}
999
1000/*
1001 * Wrapper for platform dependent unsetenv function.
1002 */
1003int
1004UnsetEnv(char *name)
1005{
1006 int ret;
1007 char *buf = JLI_MemAlloc(JLI_StrLen(name) + 2);
1008 buf = JLI_StrCat(JLI_StrCpy(buf, name), "=");
1009 ret = _putenv(buf);
1010 JLI_MemFree(buf);
1011 return (ret);
1012}
1013
1014/* --- Splash Screen shared library support --- */
1015
1016static const char* SPLASHSCREEN_SO = "\\bin\\splashscreen.dll";
1017
1018static HMODULE hSplashLib = NULL;
1019
1020void* SplashProcAddress(const char* name) {
1021 char libraryPath[MAXPATHLEN]; /* some extra space for JLI_StrCat'ing SPLASHSCREEN_SO */
1022
1023 if (!GetJREPath(libraryPath, MAXPATHLEN)) {
1024 return NULL;
1025 }
1026 if (JLI_StrLen(libraryPath)+JLI_StrLen(SPLASHSCREEN_SO) >= MAXPATHLEN) {
1027 return NULL;
1028 }
1029 JLI_StrCat(libraryPath, SPLASHSCREEN_SO);
1030
1031 if (!hSplashLib) {
1032 hSplashLib = LoadLibrary(libraryPath);
1033 }
1034 if (hSplashLib) {
1035 return GetProcAddress(hSplashLib, name);
1036 } else {
1037 return NULL;
1038 }
1039}
1040
1041void SplashFreeLibrary() {
1042 if (hSplashLib) {
1043 FreeLibrary(hSplashLib);
1044 hSplashLib = NULL;
1045 }
1046}
1047
1048const char *
1049jlong_format_specifier() {
1050 return "%I64d";
1051}
1052
1053/*
1054 * Block current thread and continue execution in a new thread
1055 */
1056int
1057ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void * args) {
1058 int rslt = 0;
1059 unsigned thread_id;
1060
1061#ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
1062#define STACK_SIZE_PARAM_IS_A_RESERVATION (0x10000)
1063#endif
1064
1065 /*
1066 * STACK_SIZE_PARAM_IS_A_RESERVATION is what we want, but it's not
1067 * supported on older version of Windows. Try first with the flag; and
1068 * if that fails try again without the flag. See MSDN document or HotSpot
1069 * source (os_win32.cpp) for details.
1070 */
1071 HANDLE thread_handle =
1072 (HANDLE)_beginthreadex(NULL,
1073 (unsigned)stack_size,
1074 continuation,
1075 args,
1076 STACK_SIZE_PARAM_IS_A_RESERVATION,
1077 &thread_id);
1078 if (thread_handle == NULL) {
1079 thread_handle =
1080 (HANDLE)_beginthreadex(NULL,
1081 (unsigned)stack_size,
1082 continuation,
1083 args,
1084 0,
1085 &thread_id);
1086 }
1087 if (thread_handle) {
1088 WaitForSingleObject(thread_handle, INFINITE);
1089 GetExitCodeThread(thread_handle, &rslt);
1090 CloseHandle(thread_handle);
1091 } else {
1092 rslt = continuation(args);
1093 }
1094 return rslt;
1095}
1096
ksrini20a64b22008-09-24 15:07:41 -07001097/* Unix only, empty on windows. */
duke6e45e102007-12-01 00:00:00 +00001098void SetJavaLauncherPlatformProps() {}
ksrini52cded22008-03-06 07:51:28 -08001099
ksrini20a64b22008-09-24 15:07:41 -07001100/*
1101 * The implementation for finding classes from the bootstrap
1102 * class loader, refer to java.h
1103 */
1104static FindClassFromBootLoader_t *findBootClass = NULL;
1105
1106jclass FindBootStrapClass(JNIEnv *env, const char *classname)
1107{
1108 HMODULE hJvm;
1109
1110 if (findBootClass == NULL) {
1111 hJvm = GetModuleHandle(JVM_DLL);
1112 if (hJvm == NULL) return NULL;
1113 /* need to use the demangled entry point */
1114 findBootClass = (FindClassFromBootLoader_t *)GetProcAddress(hJvm,
mchungb2ce9412009-08-06 16:35:24 -07001115 "JVM_FindClassFromBootLoader");
ksrini20a64b22008-09-24 15:07:41 -07001116 if (findBootClass == NULL) {
mchungb2ce9412009-08-06 16:35:24 -07001117 JLI_ReportErrorMessage(DLL_ERROR4, "JVM_FindClassFromBootLoader");
ksrini20a64b22008-09-24 15:07:41 -07001118 return NULL;
1119 }
1120 }
mchungb2ce9412009-08-06 16:35:24 -07001121 return findBootClass(env, classname);
ksrini20a64b22008-09-24 15:07:41 -07001122}
1123
ksrini52cded22008-03-06 07:51:28 -08001124void
1125InitLauncher(boolean javaw)
1126{
1127 INITCOMMONCONTROLSEX icx;
1128
1129 /*
1130 * Required for javaw mode MessageBox output as well as for
1131 * HotSpot -XX:+ShowMessageBoxOnError in java mode, an empty
1132 * flag field is sufficient to perform the basic UI initialization.
1133 */
1134 memset(&icx, 0, sizeof(INITCOMMONCONTROLSEX));
1135 icx.dwSize = sizeof(INITCOMMONCONTROLSEX);
1136 InitCommonControlsEx(&icx);
1137 _isjavaw = javaw;
1138 JLI_SetTraceLauncher();
1139}