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