1 /*
2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
3  * 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.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle 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 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.
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>
36 #include <commctrl.h>
37 
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"
44 
45 /*
46  * Prototypes.
47  */
48 static jboolean GetPublicJREHome(char *path, jint pathsize);
49 static jboolean GetJVMPath(const char *jrepath, const char *jvmtype,
50                            char *jvmpath, jint jvmpathsize);
51 static jboolean GetJREPath(char *path, jint pathsize);
52 
53 /* We supports warmup for UI stack that is performed in parallel
54  * to VM initialization.
55  * This helps to improve startup of UI application as warmup phase
56  * might be long due to initialization of OS or hardware resources.
57  * It is not CPU bound and therefore it does not interfere with VM init.
58  * Obviously such warmup only has sense for UI apps and therefore it needs
59  * to be explicitly requested by passing -Dsun.awt.warmup=true property
60  * (this is always the case for plugin/javaws).
61  *
62  * Implementation launches new thread after VM starts and use it to perform
63  * warmup code (platform dependent).
64  * This thread is later reused as AWT toolkit thread as graphics toolkit
65  * often assume that they are used from the same thread they were launched on.
66  *
67  * At the moment we only support warmup for D3D. It only possible on windows
68  * and only if other flags do not prohibit this (e.g. OpenGL support requested).
69  */
70 #undef ENABLE_AWT_PRELOAD
71 #ifndef JAVA_ARGS /* turn off AWT preloading for javac, jar, etc */
72     /* CR6999872: fastdebug crashes if awt library is loaded before JVM is
73      * initialized*/
74     #if !defined(DEBUG)
75         #define ENABLE_AWT_PRELOAD
76     #endif
77 #endif
78 
79 #ifdef ENABLE_AWT_PRELOAD
80 /* "AWT was preloaded" flag;
81  * turned on by AWTPreload().
82  */
83 int awtPreloaded = 0;
84 
85 /* Calls a function with the name specified
86  * the function must be int(*fn)(void).
87  */
88 int AWTPreload(const char *funcName);
89 /* stops AWT preloading */
90 void AWTPreloadStop();
91 
92 /* D3D preloading */
93 /* -1: not initialized; 0: OFF, 1: ON */
94 int awtPreloadD3D = -1;
95 /* command line parameter to swith D3D preloading on */
96 #define PARAM_PRELOAD_D3D "-Dsun.awt.warmup"
97 /* D3D/OpenGL management parameters */
98 #define PARAM_NODDRAW "-Dsun.java2d.noddraw"
99 #define PARAM_D3D "-Dsun.java2d.d3d"
100 #define PARAM_OPENGL "-Dsun.java2d.opengl"
101 /* funtion in awt.dll (src/windows/native/sun/java2d/d3d/D3DPipelineManager.cpp) */
102 #define D3D_PRELOAD_FUNC "preloadD3D"
103 
104 /* Extracts value of a parameter with the specified name
105  * from command line argument (returns pointer in the argument).
106  * Returns NULL if the argument does not contains the parameter.
107  * e.g.:
108  * GetParamValue("theParam", "theParam=value") returns pointer to "value".
109  */
GetParamValue(const char * paramName,const char * arg)110 const char * GetParamValue(const char *paramName, const char *arg) {
111     int nameLen = JLI_StrLen(paramName);
112     if (JLI_StrNCmp(paramName, arg, nameLen) == 0) {
113         /* arg[nameLen] is valid (may contain final NULL) */
114         if (arg[nameLen] == '=') {
115             return arg + nameLen + 1;
116         }
117     }
118     return NULL;
119 }
120 
121 /* Checks if commandline argument contains property specified
122  * and analyze it as boolean property (true/false).
123  * Returns -1 if the argument does not contain the parameter;
124  * Returns 1 if the argument contains the parameter and its value is "true";
125  * Returns 0 if the argument contains the parameter and its value is "false".
126  */
GetBoolParamValue(const char * paramName,const char * arg)127 int GetBoolParamValue(const char *paramName, const char *arg) {
128     const char * paramValue = GetParamValue(paramName, arg);
129     if (paramValue != NULL) {
130         if (JLI_StrCaseCmp(paramValue, "true") == 0) {
131             return 1;
132         }
133         if (JLI_StrCaseCmp(paramValue, "false") == 0) {
134             return 0;
135         }
136     }
137     return -1;
138 }
139 #endif /* ENABLE_AWT_PRELOAD */
140 
141 
142 static jboolean _isjavaw = JNI_FALSE;
143 
144 
145 jboolean
IsJavaw()146 IsJavaw()
147 {
148     return _isjavaw;
149 }
150 
151 /*
152  * Returns the arch path, to get the current arch use the
153  * macro GetArch, nbits here is ignored for now.
154  */
155 const char *
GetArchPath(int nbits)156 GetArchPath(int nbits)
157 {
158 #ifdef _M_AMD64
159     return "amd64";
160 #elif defined(_M_IA64)
161     return "ia64";
162 #else
163     return "i386";
164 #endif
165 }
166 
167 /*
168  *
169  */
170 void
CreateExecutionEnvironment(int * pargc,char *** pargv,char * jrepath,jint so_jrepath,char * jvmpath,jint so_jvmpath,char * jvmcfg,jint so_jvmcfg)171 CreateExecutionEnvironment(int *pargc, char ***pargv,
172                            char *jrepath, jint so_jrepath,
173                            char *jvmpath, jint so_jvmpath,
174                            char *jvmcfg,  jint so_jvmcfg) {
175     char * jvmtype;
176     int i = 0;
177     int running = CURRENT_DATA_MODEL;
178 
179     int wanted = running;
180 
181     char** argv = *pargv;
182     for (i = 1; i < *pargc ; i++) {
183         if (JLI_StrCmp(argv[i], "-J-d64") == 0 || JLI_StrCmp(argv[i], "-d64") == 0) {
184             wanted = 64;
185             continue;
186         }
187         if (JLI_StrCmp(argv[i], "-J-d32") == 0 || JLI_StrCmp(argv[i], "-d32") == 0) {
188             wanted = 32;
189             continue;
190         }
191 
192         if (IsJavaArgs() && argv[i][0] != '-')
193             continue;
194         if (argv[i][0] != '-')
195             break;
196     }
197     if (running != wanted) {
198         JLI_ReportErrorMessage(JRE_ERROR2, wanted);
199         exit(1);
200     }
201 
202     /* Find out where the JRE is that we will be using. */
203     if (!GetJREPath(jrepath, so_jrepath)) {
204         JLI_ReportErrorMessage(JRE_ERROR1);
205         exit(2);
206     }
207 
208     JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%s%s%sjvm.cfg",
209         jrepath, FILESEP, FILESEP, (char*)GetArch(), FILESEP);
210 
211     /* Find the specified JVM type */
212     if (ReadKnownVMs(jvmcfg, JNI_FALSE) < 1) {
213         JLI_ReportErrorMessage(CFG_ERROR7);
214         exit(1);
215     }
216 
217     jvmtype = CheckJvmType(pargc, pargv, JNI_FALSE);
218     if (JLI_StrCmp(jvmtype, "ERROR") == 0) {
219         JLI_ReportErrorMessage(CFG_ERROR9);
220         exit(4);
221     }
222 
223     jvmpath[0] = '\0';
224     if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath)) {
225         JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath);
226         exit(4);
227     }
228     /* If we got here, jvmpath has been correctly initialized. */
229 
230     /* Check if we need preload AWT */
231 #ifdef ENABLE_AWT_PRELOAD
232     argv = *pargv;
233     for (i = 0; i < *pargc ; i++) {
234         /* Tests the "turn on" parameter only if not set yet. */
235         if (awtPreloadD3D < 0) {
236             if (GetBoolParamValue(PARAM_PRELOAD_D3D, argv[i]) == 1) {
237                 awtPreloadD3D = 1;
238             }
239         }
240         /* Test parameters which can disable preloading if not already disabled. */
241         if (awtPreloadD3D != 0) {
242             if (GetBoolParamValue(PARAM_NODDRAW, argv[i]) == 1
243                 || GetBoolParamValue(PARAM_D3D, argv[i]) == 0
244                 || GetBoolParamValue(PARAM_OPENGL, argv[i]) == 1)
245             {
246                 awtPreloadD3D = 0;
247                 /* no need to test the rest of the parameters */
248                 break;
249             }
250         }
251     }
252 #endif /* ENABLE_AWT_PRELOAD */
253 }
254 
255 
256 static jboolean
LoadMSVCRT()257 LoadMSVCRT()
258 {
259     // Only do this once
260     static int loaded = 0;
261     char crtpath[MAXPATHLEN];
262 
263     if (!loaded) {
264         /*
265          * The Microsoft C Runtime Library needs to be loaded first.  A copy is
266          * assumed to be present in the "JRE path" directory.  If it is not found
267          * there (or "JRE path" fails to resolve), skip the explicit load and let
268          * nature take its course, which is likely to be a failure to execute.
269          * The makefiles will provide the correct lib contained in quotes in the
270          * macro MSVCR_DLL_NAME.
271          */
272 #ifdef MSVCR_DLL_NAME
273         if (GetJREPath(crtpath, MAXPATHLEN)) {
274             if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") +
275                     JLI_StrLen(MSVCR_DLL_NAME) >= MAXPATHLEN) {
276                 JLI_ReportErrorMessage(JRE_ERROR11);
277                 return JNI_FALSE;
278             }
279             (void)JLI_StrCat(crtpath, "\\bin\\" MSVCR_DLL_NAME);   /* Add crt dll */
280             JLI_TraceLauncher("CRT path is %s\n", crtpath);
281             if (_access(crtpath, 0) == 0) {
282                 if (LoadLibrary(crtpath) == 0) {
283                     JLI_ReportErrorMessage(DLL_ERROR4, crtpath);
284                     return JNI_FALSE;
285                 }
286             }
287         }
288 #endif /* MSVCR_DLL_NAME */
289 #ifdef MSVCP_DLL_NAME
290         if (GetJREPath(crtpath, MAXPATHLEN)) {
291             if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") +
292                     JLI_StrLen(MSVCP_DLL_NAME) >= MAXPATHLEN) {
293                 JLI_ReportErrorMessage(JRE_ERROR11);
294                 return JNI_FALSE;
295             }
296             (void)JLI_StrCat(crtpath, "\\bin\\" MSVCP_DLL_NAME);   /* Add prt dll */
297             JLI_TraceLauncher("PRT path is %s\n", crtpath);
298             if (_access(crtpath, 0) == 0) {
299                 if (LoadLibrary(crtpath) == 0) {
300                     JLI_ReportErrorMessage(DLL_ERROR4, crtpath);
301                     return JNI_FALSE;
302                 }
303             }
304         }
305 #endif /* MSVCP_DLL_NAME */
306         loaded = 1;
307     }
308     return JNI_TRUE;
309 }
310 
311 
312 /*
313  * Find path to JRE based on .exe's location or registry settings.
314  */
315 jboolean
GetJREPath(char * path,jint pathsize)316 GetJREPath(char *path, jint pathsize)
317 {
318     char javadll[MAXPATHLEN];
319     struct stat s;
320 
321     if (GetApplicationHome(path, pathsize)) {
322         /* Is JRE co-located with the application? */
323         JLI_Snprintf(javadll, sizeof(javadll), "%s\\bin\\" JAVA_DLL, path);
324         if (stat(javadll, &s) == 0) {
325             JLI_TraceLauncher("JRE path is %s\n", path);
326             return JNI_TRUE;
327         }
328         /* ensure storage for path + \jre + NULL */
329         if ((JLI_StrLen(path) + 4 + 1) > pathsize) {
330             JLI_TraceLauncher("Insufficient space to store JRE path\n");
331             return JNI_FALSE;
332         }
333         /* Does this app ship a private JRE in <apphome>\jre directory? */
334         JLI_Snprintf(javadll, sizeof (javadll), "%s\\jre\\bin\\" JAVA_DLL, path);
335         if (stat(javadll, &s) == 0) {
336             JLI_StrCat(path, "\\jre");
337             JLI_TraceLauncher("JRE path is %s\n", path);
338             return JNI_TRUE;
339         }
340     }
341 
342     /* Look for a public JRE on this machine. */
343     if (GetPublicJREHome(path, pathsize)) {
344         JLI_TraceLauncher("JRE path is %s\n", path);
345         return JNI_TRUE;
346     }
347 
348     JLI_ReportErrorMessage(JRE_ERROR8 JAVA_DLL);
349     return JNI_FALSE;
350 
351 }
352 
353 /*
354  * Given a JRE location and a JVM type, construct what the name the
355  * JVM shared library will be.  Return true, if such a library
356  * exists, false otherwise.
357  */
358 static jboolean
GetJVMPath(const char * jrepath,const char * jvmtype,char * jvmpath,jint jvmpathsize)359 GetJVMPath(const char *jrepath, const char *jvmtype,
360            char *jvmpath, jint jvmpathsize)
361 {
362     struct stat s;
363     if (JLI_StrChr(jvmtype, '/') || JLI_StrChr(jvmtype, '\\')) {
364         JLI_Snprintf(jvmpath, jvmpathsize, "%s\\" JVM_DLL, jvmtype);
365     } else {
366         JLI_Snprintf(jvmpath, jvmpathsize, "%s\\bin\\%s\\" JVM_DLL,
367                      jrepath, jvmtype);
368     }
369     if (stat(jvmpath, &s) == 0) {
370         return JNI_TRUE;
371     } else {
372         return JNI_FALSE;
373     }
374 }
375 
376 /*
377  * Load a jvm from "jvmpath" and initialize the invocation functions.
378  */
379 jboolean
LoadJavaVM(const char * jvmpath,InvocationFunctions * ifn)380 LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)
381 {
382     HINSTANCE handle;
383 
384     JLI_TraceLauncher("JVM path is %s\n", jvmpath);
385 
386     /*
387      * The Microsoft C Runtime Library needs to be loaded first.  A copy is
388      * assumed to be present in the "JRE path" directory.  If it is not found
389      * there (or "JRE path" fails to resolve), skip the explicit load and let
390      * nature take its course, which is likely to be a failure to execute.
391      *
392      */
393     LoadMSVCRT();
394 
395     /* Load the Java VM DLL */
396     if ((handle = LoadLibrary(jvmpath)) == 0) {
397         JLI_ReportErrorMessage(DLL_ERROR4, (char *)jvmpath);
398         return JNI_FALSE;
399     }
400 
401     /* Now get the function addresses */
402     ifn->CreateJavaVM =
403         (void *)GetProcAddress(handle, "JNI_CreateJavaVM");
404     ifn->GetDefaultJavaVMInitArgs =
405         (void *)GetProcAddress(handle, "JNI_GetDefaultJavaVMInitArgs");
406     if (ifn->CreateJavaVM == 0 || ifn->GetDefaultJavaVMInitArgs == 0) {
407         JLI_ReportErrorMessage(JNI_ERROR1, (char *)jvmpath);
408         return JNI_FALSE;
409     }
410 
411     return JNI_TRUE;
412 }
413 
414 /*
415  * If app is "c:\foo\bin\javac", then put "c:\foo" into buf.
416  */
417 jboolean
GetApplicationHome(char * buf,jint bufsize)418 GetApplicationHome(char *buf, jint bufsize)
419 {
420     char *cp;
421     GetModuleFileName(0, buf, bufsize);
422     *JLI_StrRChr(buf, '\\') = '\0'; /* remove .exe file name */
423     if ((cp = JLI_StrRChr(buf, '\\')) == 0) {
424         /* This happens if the application is in a drive root, and
425          * there is no bin directory. */
426         buf[0] = '\0';
427         return JNI_FALSE;
428     }
429     *cp = '\0';  /* remove the bin\ part */
430     return JNI_TRUE;
431 }
432 
433 /*
434  * Helpers to look in the registry for a public JRE.
435  */
436                     /* Same for 1.5.0, 1.5.1, 1.5.2 etc. */
437 #define JRE_KEY     "Software\\JavaSoft\\Java Runtime Environment"
438 
439 static jboolean
GetStringFromRegistry(HKEY key,const char * name,char * buf,jint bufsize)440 GetStringFromRegistry(HKEY key, const char *name, char *buf, jint bufsize)
441 {
442     DWORD type, size;
443 
444     if (RegQueryValueEx(key, name, 0, &type, 0, &size) == 0
445         && type == REG_SZ
446         && (size < (unsigned int)bufsize)) {
447         if (RegQueryValueEx(key, name, 0, 0, buf, &size) == 0) {
448             return JNI_TRUE;
449         }
450     }
451     return JNI_FALSE;
452 }
453 
454 static jboolean
GetPublicJREHome(char * buf,jint bufsize)455 GetPublicJREHome(char *buf, jint bufsize)
456 {
457     HKEY key, subkey;
458     char version[MAXPATHLEN];
459 
460     /*
461      * Note: There is a very similar implementation of the following
462      * registry reading code in the Windows java control panel (javacp.cpl).
463      * If there are bugs here, a similar bug probably exists there.  Hence,
464      * changes here require inspection there.
465      */
466 
467     /* Find the current version of the JRE */
468     if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, JRE_KEY, 0, KEY_READ, &key) != 0) {
469         JLI_ReportErrorMessage(REG_ERROR1, JRE_KEY);
470         return JNI_FALSE;
471     }
472 
473     if (!GetStringFromRegistry(key, "CurrentVersion",
474                                version, sizeof(version))) {
475         JLI_ReportErrorMessage(REG_ERROR2, JRE_KEY);
476         RegCloseKey(key);
477         return JNI_FALSE;
478     }
479 
480     if (JLI_StrCmp(version, GetDotVersion()) != 0) {
481         JLI_ReportErrorMessage(REG_ERROR3, JRE_KEY, version, GetDotVersion()
482         );
483         RegCloseKey(key);
484         return JNI_FALSE;
485     }
486 
487     /* Find directory where the current version is installed. */
488     if (RegOpenKeyEx(key, version, 0, KEY_READ, &subkey) != 0) {
489         JLI_ReportErrorMessage(REG_ERROR1, JRE_KEY, version);
490         RegCloseKey(key);
491         return JNI_FALSE;
492     }
493 
494     if (!GetStringFromRegistry(subkey, "JavaHome", buf, bufsize)) {
495         JLI_ReportErrorMessage(REG_ERROR4, JRE_KEY, version);
496         RegCloseKey(key);
497         RegCloseKey(subkey);
498         return JNI_FALSE;
499     }
500 
501     if (JLI_IsTraceLauncher()) {
502         char micro[MAXPATHLEN];
503         if (!GetStringFromRegistry(subkey, "MicroVersion", micro,
504                                    sizeof(micro))) {
505             printf("Warning: Can't read MicroVersion\n");
506             micro[0] = '\0';
507         }
508         printf("Version major.minor.micro = %s.%s\n", version, micro);
509     }
510 
511     RegCloseKey(key);
512     RegCloseKey(subkey);
513     return JNI_TRUE;
514 }
515 
516 /*
517  * Support for doing cheap, accurate interval timing.
518  */
519 static jboolean counterAvailable = JNI_FALSE;
520 static jboolean counterInitialized = JNI_FALSE;
521 static LARGE_INTEGER counterFrequency;
522 
CounterGet()523 jlong CounterGet()
524 {
525     LARGE_INTEGER count;
526 
527     if (!counterInitialized) {
528         counterAvailable = QueryPerformanceFrequency(&counterFrequency);
529         counterInitialized = JNI_TRUE;
530     }
531     if (!counterAvailable) {
532         return 0;
533     }
534     QueryPerformanceCounter(&count);
535     return (jlong)(count.QuadPart);
536 }
537 
Counter2Micros(jlong counts)538 jlong Counter2Micros(jlong counts)
539 {
540     if (!counterAvailable || !counterInitialized) {
541         return 0;
542     }
543     return (counts * 1000 * 1000)/counterFrequency.QuadPart;
544 }
545 /*
546  * windows snprintf does not guarantee a null terminator in the buffer,
547  * if the computed size is equal to or greater than the buffer size,
548  * as well as error conditions. This function guarantees a null terminator
549  * under all these conditions. An unreasonable buffer or size will return
550  * an error value. Under all other conditions this function will return the
551  * size of the bytes actually written minus the null terminator, similar
552  * to ansi snprintf api. Thus when calling this function the caller must
553  * ensure storage for the null terminator.
554  */
555 int
JLI_Snprintf(char * buffer,size_t size,const char * format,...)556 JLI_Snprintf(char* buffer, size_t size, const char* format, ...) {
557     int rc;
558     va_list vl;
559     if (size == 0 || buffer == NULL)
560         return -1;
561     buffer[0] = '\0';
562     va_start(vl, format);
563     rc = vsnprintf(buffer, size, format, vl);
564     va_end(vl);
565     /* force a null terminator, if something is amiss */
566     if (rc < 0) {
567         /* apply ansi semantics */
568         buffer[size - 1] = '\0';
569         return size;
570     } else if (rc == size) {
571         /* force a null terminator */
572         buffer[size - 1] = '\0';
573     }
574     return rc;
575 }
576 
577 void
JLI_ReportErrorMessage(const char * fmt,...)578 JLI_ReportErrorMessage(const char* fmt, ...) {
579     va_list vl;
580     va_start(vl,fmt);
581 
582     if (IsJavaw()) {
583         char *message;
584 
585         /* get the length of the string we need */
586         int n = _vscprintf(fmt, vl);
587 
588         message = (char *)JLI_MemAlloc(n + 1);
589         _vsnprintf(message, n, fmt, vl);
590         message[n]='\0';
591         MessageBox(NULL, message, "Java Virtual Machine Launcher",
592             (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
593         JLI_MemFree(message);
594     } else {
595         vfprintf(stderr, fmt, vl);
596         fprintf(stderr, "\n");
597     }
598     va_end(vl);
599 }
600 
601 /*
602  * Just like JLI_ReportErrorMessage, except that it concatenates the system
603  * error message if any, its upto the calling routine to correctly
604  * format the separation of the messages.
605  */
606 void
JLI_ReportErrorMessageSys(const char * fmt,...)607 JLI_ReportErrorMessageSys(const char *fmt, ...)
608 {
609     va_list vl;
610 
611     int save_errno = errno;
612     DWORD       errval;
613     jboolean freeit = JNI_FALSE;
614     char  *errtext = NULL;
615 
616     va_start(vl, fmt);
617 
618     if ((errval = GetLastError()) != 0) {               /* Platform SDK / DOS Error */
619         int n = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|
620             FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_ALLOCATE_BUFFER,
621             NULL, errval, 0, (LPTSTR)&errtext, 0, NULL);
622         if (errtext == NULL || n == 0) {                /* Paranoia check */
623             errtext = "";
624             n = 0;
625         } else {
626             freeit = JNI_TRUE;
627             if (n > 2) {                                /* Drop final CR, LF */
628                 if (errtext[n - 1] == '\n') n--;
629                 if (errtext[n - 1] == '\r') n--;
630                 errtext[n] = '\0';
631             }
632         }
633     } else {   /* C runtime error that has no corresponding DOS error code */
634         errtext = strerror(save_errno);
635     }
636 
637     if (IsJavaw()) {
638         char *message;
639         int mlen;
640         /* get the length of the string we need */
641         int len = mlen =  _vscprintf(fmt, vl) + 1;
642         if (freeit) {
643            mlen += (int)JLI_StrLen(errtext);
644         }
645 
646         message = (char *)JLI_MemAlloc(mlen);
647         _vsnprintf(message, len, fmt, vl);
648         message[len]='\0';
649 
650         if (freeit) {
651            JLI_StrCat(message, errtext);
652         }
653 
654         MessageBox(NULL, message, "Java Virtual Machine Launcher",
655             (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
656 
657         JLI_MemFree(message);
658     } else {
659         vfprintf(stderr, fmt, vl);
660         if (freeit) {
661            fprintf(stderr, "%s", errtext);
662         }
663     }
664     if (freeit) {
665         (void)LocalFree((HLOCAL)errtext);
666     }
667     va_end(vl);
668 }
669 
JLI_ReportExceptionDescription(JNIEnv * env)670 void  JLI_ReportExceptionDescription(JNIEnv * env) {
671     if (IsJavaw()) {
672        /*
673         * This code should be replaced by code which opens a window with
674         * the exception detail message, for now atleast put a dialog up.
675         */
676         MessageBox(NULL, "A Java Exception has occurred.", "Java Virtual Machine Launcher",
677                (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
678     } else {
679         (*env)->ExceptionDescribe(env);
680     }
681 }
682 
683 jboolean
ServerClassMachine()684 ServerClassMachine() {
685     return (GetErgoPolicy() == ALWAYS_SERVER_CLASS) ? JNI_TRUE : JNI_FALSE;
686 }
687 
688 /*
689  * Determine if there is an acceptable JRE in the registry directory top_key.
690  * Upon locating the "best" one, return a fully qualified path to it.
691  * "Best" is defined as the most advanced JRE meeting the constraints
692  * contained in the manifest_info. If no JRE in this directory meets the
693  * constraints, return NULL.
694  *
695  * It doesn't matter if we get an error reading the registry, or we just
696  * don't find anything interesting in the directory.  We just return NULL
697  * in either case.
698  */
699 static char *
ProcessDir(manifest_info * info,HKEY top_key)700 ProcessDir(manifest_info* info, HKEY top_key) {
701     DWORD   index = 0;
702     HKEY    ver_key;
703     char    name[MAXNAMELEN];
704     int     len;
705     char    *best = NULL;
706 
707     /*
708      * Enumerate "<top_key>/SOFTWARE/JavaSoft/Java Runtime Environment"
709      * searching for the best available version.
710      */
711     while (RegEnumKey(top_key, index, name, MAXNAMELEN) == ERROR_SUCCESS) {
712         index++;
713         if (JLI_AcceptableRelease(name, info->jre_version))
714             if ((best == NULL) || (JLI_ExactVersionId(name, best) > 0)) {
715                 if (best != NULL)
716                     JLI_MemFree(best);
717                 best = JLI_StringDup(name);
718             }
719     }
720 
721     /*
722      * Extract "JavaHome" from the "best" registry directory and return
723      * that path.  If no appropriate version was located, or there is an
724      * error in extracting the "JavaHome" string, return null.
725      */
726     if (best == NULL)
727         return (NULL);
728     else {
729         if (RegOpenKeyEx(top_key, best, 0, KEY_READ, &ver_key)
730           != ERROR_SUCCESS) {
731             JLI_MemFree(best);
732             if (ver_key != NULL)
733                 RegCloseKey(ver_key);
734             return (NULL);
735         }
736         JLI_MemFree(best);
737         len = MAXNAMELEN;
738         if (RegQueryValueEx(ver_key, "JavaHome", NULL, NULL, (LPBYTE)name, &len)
739           != ERROR_SUCCESS) {
740             if (ver_key != NULL)
741                 RegCloseKey(ver_key);
742             return (NULL);
743         }
744         if (ver_key != NULL)
745             RegCloseKey(ver_key);
746         return (JLI_StringDup(name));
747     }
748 }
749 
750 /*
751  * This is the global entry point. It examines the host for the optimal
752  * JRE to be used by scanning a set of registry entries.  This set of entries
753  * is hardwired on Windows as "Software\JavaSoft\Java Runtime Environment"
754  * under the set of roots "{ HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }".
755  *
756  * This routine simply opens each of these registry directories before passing
757  * control onto ProcessDir().
758  */
759 char *
LocateJRE(manifest_info * info)760 LocateJRE(manifest_info* info) {
761     HKEY    key = NULL;
762     char    *path;
763     int     key_index;
764     HKEY    root_keys[2] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE };
765 
766     for (key_index = 0; key_index <= 1; key_index++) {
767         if (RegOpenKeyEx(root_keys[key_index], JRE_KEY, 0, KEY_READ, &key)
768           == ERROR_SUCCESS)
769             if ((path = ProcessDir(info, key)) != NULL) {
770                 if (key != NULL)
771                     RegCloseKey(key);
772                 return (path);
773             }
774         if (key != NULL)
775             RegCloseKey(key);
776     }
777     return NULL;
778 }
779 
780 /*
781  * Local helper routine to isolate a single token (option or argument)
782  * from the command line.
783  *
784  * This routine accepts a pointer to a character pointer.  The first
785  * token (as defined by MSDN command-line argument syntax) is isolated
786  * from that string.
787  *
788  * Upon return, the input character pointer pointed to by the parameter s
789  * is updated to point to the remainding, unscanned, portion of the string,
790  * or to a null character if the entire string has been consummed.
791  *
792  * This function returns a pointer to a null-terminated string which
793  * contains the isolated first token, or to the null character if no
794  * token could be isolated.
795  *
796  * Note the side effect of modifying the input string s by the insertion
797  * of a null character, making it two strings.
798  *
799  * See "Parsing C Command-Line Arguments" in the MSDN Library for the
800  * parsing rule details.  The rule summary from that specification is:
801  *
802  *  * Arguments are delimited by white space, which is either a space or a tab.
803  *
804  *  * A string surrounded by double quotation marks is interpreted as a single
805  *    argument, regardless of white space contained within. A quoted string can
806  *    be embedded in an argument. Note that the caret (^) is not recognized as
807  *    an escape character or delimiter.
808  *
809  *  * A double quotation mark preceded by a backslash, \", is interpreted as a
810  *    literal double quotation mark (").
811  *
812  *  * Backslashes are interpreted literally, unless they immediately precede a
813  *    double quotation mark.
814  *
815  *  * If an even number of backslashes is followed by a double quotation mark,
816  *    then one backslash (\) is placed in the argv array for every pair of
817  *    backslashes (\\), and the double quotation mark (") is interpreted as a
818  *    string delimiter.
819  *
820  *  * If an odd number of backslashes is followed by a double quotation mark,
821  *    then one backslash (\) is placed in the argv array for every pair of
822  *    backslashes (\\) and the double quotation mark is interpreted as an
823  *    escape sequence by the remaining backslash, causing a literal double
824  *    quotation mark (") to be placed in argv.
825  */
826 static char*
nextarg(char ** s)827 nextarg(char** s) {
828     char    *p = *s;
829     char    *head;
830     int     slashes = 0;
831     int     inquote = 0;
832 
833     /*
834      * Strip leading whitespace, which MSDN defines as only space or tab.
835      * (Hence, no locale specific "isspace" here.)
836      */
837     while (*p != (char)0 && (*p == ' ' || *p == '\t'))
838         p++;
839     head = p;                   /* Save the start of the token to return */
840 
841     /*
842      * Isolate a token from the command line.
843      */
844     while (*p != (char)0 && (inquote || !(*p == ' ' || *p == '\t'))) {
845         if (*p == '\\' && *(p+1) == '"' && slashes % 2 == 0)
846             p++;
847         else if (*p == '"')
848             inquote = !inquote;
849         slashes = (*p++ == '\\') ? slashes + 1 : 0;
850     }
851 
852     /*
853      * If the token isolated isn't already terminated in a "char zero",
854      * then replace the whitespace character with one and move to the
855      * next character.
856      */
857     if (*p != (char)0)
858         *p++ = (char)0;
859 
860     /*
861      * Update the parameter to point to the head of the remaining string
862      * reflecting the command line and return a pointer to the leading
863      * token which was isolated from the command line.
864      */
865     *s = p;
866     return (head);
867 }
868 
869 /*
870  * Local helper routine to return a string equivalent to the input string
871  * s, but with quotes removed so the result is a string as would be found
872  * in argv[].  The returned string should be freed by a call to JLI_MemFree().
873  *
874  * The rules for quoting (and escaped quotes) are:
875  *
876  *  1 A double quotation mark preceded by a backslash, \", is interpreted as a
877  *    literal double quotation mark (").
878  *
879  *  2 Backslashes are interpreted literally, unless they immediately precede a
880  *    double quotation mark.
881  *
882  *  3 If an even number of backslashes is followed by a double quotation mark,
883  *    then one backslash (\) is placed in the argv array for every pair of
884  *    backslashes (\\), and the double quotation mark (") is interpreted as a
885  *    string delimiter.
886  *
887  *  4 If an odd number of backslashes is followed by a double quotation mark,
888  *    then one backslash (\) is placed in the argv array for every pair of
889  *    backslashes (\\) and the double quotation mark is interpreted as an
890  *    escape sequence by the remaining backslash, causing a literal double
891  *    quotation mark (") to be placed in argv.
892  */
893 static char*
unquote(const char * s)894 unquote(const char *s) {
895     const char *p = s;          /* Pointer to the tail of the original string */
896     char *un = (char*)JLI_MemAlloc(JLI_StrLen(s) + 1);  /* Ptr to unquoted string */
897     char *pun = un;             /* Pointer to the tail of the unquoted string */
898 
899     while (*p != '\0') {
900         if (*p == '"') {
901             p++;
902         } else if (*p == '\\') {
903             const char *q = p + JLI_StrSpn(p,"\\");
904             if (*q == '"')
905                 do {
906                     *pun++ = '\\';
907                     p += 2;
908                  } while (*p == '\\' && p < q);
909             else
910                 while (p < q)
911                     *pun++ = *p++;
912         } else {
913             *pun++ = *p++;
914         }
915     }
916     *pun = '\0';
917     return un;
918 }
919 
920 /*
921  * Given a path to a jre to execute, this routine checks if this process
922  * is indeed that jre.  If not, it exec's that jre.
923  *
924  * We want to actually check the paths rather than just the version string
925  * built into the executable, so that given version specification will yield
926  * the exact same Java environment, regardless of the version of the arbitrary
927  * launcher we start with.
928  */
929 void
ExecJRE(char * jre,char ** argv)930 ExecJRE(char *jre, char **argv) {
931     jint     len;
932     char    path[MAXPATHLEN + 1];
933 
934     const char *progname = GetProgramName();
935 
936     /*
937      * Resolve the real path to the currently running launcher.
938      */
939     len = GetModuleFileName(NULL, path, MAXPATHLEN + 1);
940     if (len == 0 || len > MAXPATHLEN) {
941         JLI_ReportErrorMessageSys(JRE_ERROR9, progname);
942         exit(1);
943     }
944 
945     JLI_TraceLauncher("ExecJRE: old: %s\n", path);
946     JLI_TraceLauncher("ExecJRE: new: %s\n", jre);
947 
948     /*
949      * If the path to the selected JRE directory is a match to the initial
950      * portion of the path to the currently executing JRE, we have a winner!
951      * If so, just return.
952      */
953     if (JLI_StrNCaseCmp(jre, path, JLI_StrLen(jre)) == 0)
954         return;                 /* I am the droid you were looking for */
955 
956     /*
957      * If this isn't the selected version, exec the selected version.
958      */
959     JLI_Snprintf(path, sizeof(path), "%s\\bin\\%s.exe", jre, progname);
960 
961     /*
962      * Although Windows has an execv() entrypoint, it doesn't actually
963      * overlay a process: it can only create a new process and terminate
964      * the old process.  Therefore, any processes waiting on the initial
965      * process wake up and they shouldn't.  Hence, a chain of pseudo-zombie
966      * processes must be retained to maintain the proper wait semantics.
967      * Fortunately the image size of the launcher isn't too large at this
968      * time.
969      *
970      * If it weren't for this semantic flaw, the code below would be ...
971      *
972      *     execv(path, argv);
973      *     JLI_ReportErrorMessage("Error: Exec of %s failed\n", path);
974      *     exit(1);
975      *
976      * The incorrect exec semantics could be addressed by:
977      *
978      *     exit((int)spawnv(_P_WAIT, path, argv));
979      *
980      * Unfortunately, a bug in Windows spawn/exec impementation prevents
981      * this from completely working.  All the Windows POSIX process creation
982      * interfaces are implemented as wrappers around the native Windows
983      * function CreateProcess().  CreateProcess() takes a single string
984      * to specify command line options and arguments, so the POSIX routine
985      * wrappers build a single string from the argv[] array and in the
986      * process, any quoting information is lost.
987      *
988      * The solution to this to get the original command line, to process it
989      * to remove the new multiple JRE options (if any) as was done for argv
990      * in the common SelectVersion() routine and finally to pass it directly
991      * to the native CreateProcess() Windows process control interface.
992      */
993     {
994         char    *cmdline;
995         char    *p;
996         char    *np;
997         char    *ocl;
998         char    *ccl;
999         char    *unquoted;
1000         DWORD   exitCode;
1001         STARTUPINFO si;
1002         PROCESS_INFORMATION pi;
1003 
1004         /*
1005          * The following code block gets and processes the original command
1006          * line, replacing the argv[0] equivalent in the command line with
1007          * the path to the new executable and removing the appropriate
1008          * Multiple JRE support options. Note that similar logic exists
1009          * in the platform independent SelectVersion routine, but is
1010          * replicated here due to the syntax of CreateProcess().
1011          *
1012          * The magic "+ 4" characters added to the command line length are
1013          * 2 possible quotes around the path (argv[0]), a space after the
1014          * path and a terminating null character.
1015          */
1016         ocl = GetCommandLine();
1017         np = ccl = JLI_StringDup(ocl);
1018         p = nextarg(&np);               /* Discard argv[0] */
1019         cmdline = (char *)JLI_MemAlloc(JLI_StrLen(path) + JLI_StrLen(np) + 4);
1020         if (JLI_StrChr(path, (int)' ') == NULL && JLI_StrChr(path, (int)'\t') == NULL)
1021             cmdline = JLI_StrCpy(cmdline, path);
1022         else
1023             cmdline = JLI_StrCat(JLI_StrCat(JLI_StrCpy(cmdline, "\""), path), "\"");
1024 
1025         while (*np != (char)0) {                /* While more command-line */
1026             p = nextarg(&np);
1027             if (*p != (char)0) {                /* If a token was isolated */
1028                 unquoted = unquote(p);
1029                 if (*unquoted == '-') {         /* Looks like an option */
1030                     if (JLI_StrCmp(unquoted, "-classpath") == 0 ||
1031                       JLI_StrCmp(unquoted, "-cp") == 0) {       /* Unique cp syntax */
1032                         cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
1033                         p = nextarg(&np);
1034                         if (*p != (char)0)      /* If a token was isolated */
1035                             cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
1036                     } else if (JLI_StrNCmp(unquoted, "-version:", 9) != 0 &&
1037                       JLI_StrCmp(unquoted, "-jre-restrict-search") != 0 &&
1038                       JLI_StrCmp(unquoted, "-no-jre-restrict-search") != 0) {
1039                         cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
1040                     }
1041                 } else {                        /* End of options */
1042                     cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
1043                     cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), np);
1044                     JLI_MemFree((void *)unquoted);
1045                     break;
1046                 }
1047                 JLI_MemFree((void *)unquoted);
1048             }
1049         }
1050         JLI_MemFree((void *)ccl);
1051 
1052         if (JLI_IsTraceLauncher()) {
1053             np = ccl = JLI_StringDup(cmdline);
1054             p = nextarg(&np);
1055             printf("ReExec Command: %s (%s)\n", path, p);
1056             printf("ReExec Args: %s\n", np);
1057             JLI_MemFree((void *)ccl);
1058         }
1059         (void)fflush(stdout);
1060         (void)fflush(stderr);
1061 
1062         /*
1063          * The following code is modeled after a model presented in the
1064          * Microsoft Technical Article "Moving Unix Applications to
1065          * Windows NT" (March 6, 1994) and "Creating Processes" on MSDN
1066          * (Februrary 2005).  It approximates UNIX spawn semantics with
1067          * the parent waiting for termination of the child.
1068          */
1069         memset(&si, 0, sizeof(si));
1070         si.cb =sizeof(STARTUPINFO);
1071         memset(&pi, 0, sizeof(pi));
1072 
1073         if (!CreateProcess((LPCTSTR)path,       /* executable name */
1074           (LPTSTR)cmdline,                      /* command line */
1075           (LPSECURITY_ATTRIBUTES)NULL,          /* process security attr. */
1076           (LPSECURITY_ATTRIBUTES)NULL,          /* thread security attr. */
1077           (BOOL)TRUE,                           /* inherits system handles */
1078           (DWORD)0,                             /* creation flags */
1079           (LPVOID)NULL,                         /* environment block */
1080           (LPCTSTR)NULL,                        /* current directory */
1081           (LPSTARTUPINFO)&si,                   /* (in) startup information */
1082           (LPPROCESS_INFORMATION)&pi)) {        /* (out) process information */
1083             JLI_ReportErrorMessageSys(SYS_ERROR1, path);
1084             exit(1);
1085         }
1086 
1087         if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_FAILED) {
1088             if (GetExitCodeProcess(pi.hProcess, &exitCode) == FALSE)
1089                 exitCode = 1;
1090         } else {
1091             JLI_ReportErrorMessage(SYS_ERROR2);
1092             exitCode = 1;
1093         }
1094 
1095         CloseHandle(pi.hThread);
1096         CloseHandle(pi.hProcess);
1097 
1098         exit(exitCode);
1099     }
1100 }
1101 
1102 /*
1103  * Wrapper for platform dependent unsetenv function.
1104  */
1105 int
UnsetEnv(char * name)1106 UnsetEnv(char *name)
1107 {
1108     int ret;
1109     char *buf = JLI_MemAlloc(JLI_StrLen(name) + 2);
1110     buf = JLI_StrCat(JLI_StrCpy(buf, name), "=");
1111     ret = _putenv(buf);
1112     JLI_MemFree(buf);
1113     return (ret);
1114 }
1115 
1116 /* --- Splash Screen shared library support --- */
1117 
1118 static const char* SPLASHSCREEN_SO = "\\bin\\splashscreen.dll";
1119 
1120 static HMODULE hSplashLib = NULL;
1121 
SplashProcAddress(const char * name)1122 void* SplashProcAddress(const char* name) {
1123     char libraryPath[MAXPATHLEN]; /* some extra space for JLI_StrCat'ing SPLASHSCREEN_SO */
1124 
1125     if (!GetJREPath(libraryPath, MAXPATHLEN)) {
1126         return NULL;
1127     }
1128     if (JLI_StrLen(libraryPath)+JLI_StrLen(SPLASHSCREEN_SO) >= MAXPATHLEN) {
1129         return NULL;
1130     }
1131     JLI_StrCat(libraryPath, SPLASHSCREEN_SO);
1132 
1133     if (!hSplashLib) {
1134         hSplashLib = LoadLibrary(libraryPath);
1135     }
1136     if (hSplashLib) {
1137         return GetProcAddress(hSplashLib, name);
1138     } else {
1139         return NULL;
1140     }
1141 }
1142 
SplashFreeLibrary()1143 void SplashFreeLibrary() {
1144     if (hSplashLib) {
1145         FreeLibrary(hSplashLib);
1146         hSplashLib = NULL;
1147     }
1148 }
1149 
1150 const char *
jlong_format_specifier()1151 jlong_format_specifier() {
1152     return "%I64d";
1153 }
1154 
1155 /*
1156  * Block current thread and continue execution in a new thread
1157  */
1158 int
ContinueInNewThread0(int (JNICALL * continuation)(void *),jlong stack_size,void * args)1159 ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void * args) {
1160     int rslt = 0;
1161     unsigned thread_id;
1162 
1163 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
1164 #define STACK_SIZE_PARAM_IS_A_RESERVATION  (0x10000)
1165 #endif
1166 
1167     /*
1168      * STACK_SIZE_PARAM_IS_A_RESERVATION is what we want, but it's not
1169      * supported on older version of Windows. Try first with the flag; and
1170      * if that fails try again without the flag. See MSDN document or HotSpot
1171      * source (os_win32.cpp) for details.
1172      */
1173     HANDLE thread_handle =
1174       (HANDLE)_beginthreadex(NULL,
1175                              (unsigned)stack_size,
1176                              continuation,
1177                              args,
1178                              STACK_SIZE_PARAM_IS_A_RESERVATION,
1179                              &thread_id);
1180     if (thread_handle == NULL) {
1181       thread_handle =
1182       (HANDLE)_beginthreadex(NULL,
1183                              (unsigned)stack_size,
1184                              continuation,
1185                              args,
1186                              0,
1187                              &thread_id);
1188     }
1189 
1190     /* AWT preloading (AFTER main thread start) */
1191 #ifdef ENABLE_AWT_PRELOAD
1192     /* D3D preloading */
1193     if (awtPreloadD3D != 0) {
1194         char *envValue;
1195         /* D3D routines checks env.var J2D_D3D if no appropriate
1196          * command line params was specified
1197          */
1198         envValue = getenv("J2D_D3D");
1199         if (envValue != NULL && JLI_StrCaseCmp(envValue, "false") == 0) {
1200             awtPreloadD3D = 0;
1201         }
1202         /* Test that AWT preloading isn't disabled by J2D_D3D_PRELOAD env.var */
1203         envValue = getenv("J2D_D3D_PRELOAD");
1204         if (envValue != NULL && JLI_StrCaseCmp(envValue, "false") == 0) {
1205             awtPreloadD3D = 0;
1206         }
1207         if (awtPreloadD3D < 0) {
1208             /* If awtPreloadD3D is still undefined (-1), test
1209              * if it is turned on by J2D_D3D_PRELOAD env.var.
1210              * By default it's turned OFF.
1211              */
1212             awtPreloadD3D = 0;
1213             if (envValue != NULL && JLI_StrCaseCmp(envValue, "true") == 0) {
1214                 awtPreloadD3D = 1;
1215             }
1216          }
1217     }
1218     if (awtPreloadD3D) {
1219         AWTPreload(D3D_PRELOAD_FUNC);
1220     }
1221 #endif /* ENABLE_AWT_PRELOAD */
1222 
1223     if (thread_handle) {
1224       WaitForSingleObject(thread_handle, INFINITE);
1225       GetExitCodeThread(thread_handle, &rslt);
1226       CloseHandle(thread_handle);
1227     } else {
1228       rslt = continuation(args);
1229     }
1230 
1231 #ifdef ENABLE_AWT_PRELOAD
1232     if (awtPreloaded) {
1233         AWTPreloadStop();
1234     }
1235 #endif /* ENABLE_AWT_PRELOAD */
1236 
1237     return rslt;
1238 }
1239 
1240 /* Unix only, empty on windows. */
SetJavaLauncherPlatformProps()1241 void SetJavaLauncherPlatformProps() {}
1242 
1243 /*
1244  * The implementation for finding classes from the bootstrap
1245  * class loader, refer to java.h
1246  */
1247 static FindClassFromBootLoader_t *findBootClass = NULL;
1248 
FindBootStrapClass(JNIEnv * env,const char * classname)1249 jclass FindBootStrapClass(JNIEnv *env, const char *classname)
1250 {
1251    HMODULE hJvm;
1252 
1253    if (findBootClass == NULL) {
1254        hJvm = GetModuleHandle(JVM_DLL);
1255        if (hJvm == NULL) return NULL;
1256        /* need to use the demangled entry point */
1257        findBootClass = (FindClassFromBootLoader_t *)GetProcAddress(hJvm,
1258             "JVM_FindClassFromBootLoader");
1259        if (findBootClass == NULL) {
1260           JLI_ReportErrorMessage(DLL_ERROR4, "JVM_FindClassFromBootLoader");
1261           return NULL;
1262        }
1263    }
1264    return findBootClass(env, classname);
1265 }
1266 
1267 void
InitLauncher(boolean javaw)1268 InitLauncher(boolean javaw)
1269 {
1270     INITCOMMONCONTROLSEX icx;
1271 
1272     /*
1273      * Required for javaw mode MessageBox output as well as for
1274      * HotSpot -XX:+ShowMessageBoxOnError in java mode, an empty
1275      * flag field is sufficient to perform the basic UI initialization.
1276      */
1277     memset(&icx, 0, sizeof(INITCOMMONCONTROLSEX));
1278     icx.dwSize = sizeof(INITCOMMONCONTROLSEX);
1279     InitCommonControlsEx(&icx);
1280     _isjavaw = javaw;
1281     JLI_SetTraceLauncher();
1282 }
1283 
1284 
1285 /* ============================== */
1286 /* AWT preloading */
1287 #ifdef ENABLE_AWT_PRELOAD
1288 
1289 typedef int FnPreloadStart(void);
1290 typedef void FnPreloadStop(void);
1291 static FnPreloadStop *fnPreloadStop = NULL;
1292 static HMODULE hPreloadAwt = NULL;
1293 
1294 /*
1295  * Starts AWT preloading
1296  */
AWTPreload(const char * funcName)1297 int AWTPreload(const char *funcName)
1298 {
1299     int result = -1;
1300     /* load AWT library once (if several preload function should be called) */
1301     if (hPreloadAwt == NULL) {
1302         /* awt.dll is not loaded yet */
1303         char libraryPath[MAXPATHLEN];
1304         int jrePathLen = 0;
1305         HMODULE hJava = NULL;
1306         HMODULE hVerify = NULL;
1307 
1308         while (1) {
1309             /* awt.dll depends on jvm.dll & java.dll;
1310              * jvm.dll is already loaded, so we need only java.dll;
1311              * java.dll depends on MSVCRT lib & verify.dll.
1312              */
1313             if (!GetJREPath(libraryPath, MAXPATHLEN)) {
1314                 break;
1315             }
1316 
1317             /* save path length */
1318             jrePathLen = JLI_StrLen(libraryPath);
1319 
1320             if (jrePathLen + JLI_StrLen("\\bin\\verify.dll") >= MAXPATHLEN) {
1321               /* jre path is too long, the library path will not fit there;
1322                * report and abort preloading
1323                */
1324               JLI_ReportErrorMessage(JRE_ERROR11);
1325               break;
1326             }
1327 
1328             /* load msvcrt 1st */
1329             LoadMSVCRT();
1330 
1331             /* load verify.dll */
1332             JLI_StrCat(libraryPath, "\\bin\\verify.dll");
1333             hVerify = LoadLibrary(libraryPath);
1334             if (hVerify == NULL) {
1335                 break;
1336             }
1337 
1338             /* restore jrePath */
1339             libraryPath[jrePathLen] = 0;
1340             /* load java.dll */
1341             JLI_StrCat(libraryPath, "\\bin\\" JAVA_DLL);
1342             hJava = LoadLibrary(libraryPath);
1343             if (hJava == NULL) {
1344                 break;
1345             }
1346 
1347             /* restore jrePath */
1348             libraryPath[jrePathLen] = 0;
1349             /* load awt.dll */
1350             JLI_StrCat(libraryPath, "\\bin\\awt.dll");
1351             hPreloadAwt = LoadLibrary(libraryPath);
1352             if (hPreloadAwt == NULL) {
1353                 break;
1354             }
1355 
1356             /* get "preloadStop" func ptr */
1357             fnPreloadStop = (FnPreloadStop *)GetProcAddress(hPreloadAwt, "preloadStop");
1358 
1359             break;
1360         }
1361     }
1362 
1363     if (hPreloadAwt != NULL) {
1364         FnPreloadStart *fnInit = (FnPreloadStart *)GetProcAddress(hPreloadAwt, funcName);
1365         if (fnInit != NULL) {
1366             /* don't forget to stop preloading */
1367             awtPreloaded = 1;
1368 
1369             result = fnInit();
1370         }
1371     }
1372 
1373     return result;
1374 }
1375 
1376 /*
1377  * Terminates AWT preloading
1378  */
AWTPreloadStop()1379 void AWTPreloadStop() {
1380     if (fnPreloadStop != NULL) {
1381         fnPreloadStop();
1382     }
1383 }
1384 
1385 #endif /* ENABLE_AWT_PRELOAD */
1386 
1387 int
JVMInit(InvocationFunctions * ifn,jlong threadStackSize,int argc,char ** argv,int mode,char * what,int ret)1388 JVMInit(InvocationFunctions* ifn, jlong threadStackSize,
1389         int argc, char **argv,
1390         int mode, char *what, int ret)
1391 {
1392     ShowSplashScreen();
1393     return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret);
1394 }
1395 
1396 void
PostJVMInit(JNIEnv * env,jstring mainClass,JavaVM * vm)1397 PostJVMInit(JNIEnv *env, jstring mainClass, JavaVM *vm)
1398 {
1399     // stubbed out for windows and *nixes.
1400 }
1401 
1402 void
RegisterThread()1403 RegisterThread()
1404 {
1405     // stubbed out for windows and *nixes.
1406 }
1407 
1408 /*
1409  * on windows, we return a false to indicate this option is not applicable
1410  */
1411 jboolean
ProcessPlatformOption(const char * arg)1412 ProcessPlatformOption(const char *arg)
1413 {
1414     return JNI_FALSE;
1415 }
1416 
1417 int
filterArgs(StdArg * stdargs,const int nargc,StdArg ** pargv)1418 filterArgs(StdArg *stdargs, const int nargc, StdArg **pargv) {
1419     StdArg* argv = NULL;
1420     int nargs = 0;
1421     int i;
1422 
1423     /* Copy the non-vm args */
1424     for (i = 0; i < nargc ; i++) {
1425         const char *arg = stdargs[i].arg;
1426         if (arg[0] == '-' && arg[1] == 'J')
1427             continue;
1428         argv = (StdArg*) JLI_MemRealloc(argv, (nargs+1) * sizeof(StdArg));
1429         argv[nargs].arg = JLI_StringDup(arg);
1430         argv[nargs].has_wildcard = stdargs[i].has_wildcard;
1431         nargs++;
1432     }
1433     *pargv = argv;
1434     return nargs;
1435 }
1436 
1437 /*
1438  * At this point we have the arguments to the application, and we need to
1439  * check with original stdargs in order to compare which of these truly
1440  * needs expansion. cmdtoargs will specify this if it finds a bare
1441  * (unquoted) argument containing a glob character(s) ie. * or ?
1442  */
1443 jobjectArray
CreateApplicationArgs(JNIEnv * env,char ** strv,int argc)1444 CreateApplicationArgs(JNIEnv *env, char **strv, int argc)
1445 {
1446     int i, j, idx, tlen;
1447     jobjectArray outArray, inArray;
1448     char *ostart, *astart, **nargv;
1449     jboolean needs_expansion = JNI_FALSE;
1450     jmethodID mid;
1451     int filteredargc, stdargc;
1452     StdArg *stdargs;
1453     StdArg *filteredargs;
1454     jclass cls = GetLauncherHelperClass(env);
1455     NULL_CHECK0(cls);
1456 
1457     if (argc == 0) {
1458         return NewPlatformStringArray(env, strv, argc);
1459     }
1460     // the holy grail we need to compare with.
1461     stdargs = JLI_GetStdArgs();
1462     stdargc = JLI_GetStdArgc();
1463 
1464     filteredargc = filterArgs(stdargs, stdargc, &filteredargs);
1465 
1466     // sanity check, this should never happen
1467     if (argc > stdargc) {
1468         JLI_TraceLauncher("Warning: app args is larger than the original, %d %d\n", argc, stdargc);
1469         JLI_TraceLauncher("passing arguments as-is.\n");
1470         return NewPlatformStringArray(env, strv, argc);
1471     }
1472 
1473     // sanity check, match the args we have, to the holy grail
1474     idx = filteredargc - argc;
1475     ostart = filteredargs[idx].arg;
1476     astart = strv[0];
1477     // sanity check, ensure that the first argument of the arrays are the same
1478     if (JLI_StrCmp(ostart, astart) != 0) {
1479         // some thing is amiss the args don't match
1480         JLI_TraceLauncher("Warning: app args parsing error\n");
1481         JLI_TraceLauncher("passing arguments as-is\n");
1482         return NewPlatformStringArray(env, strv, argc);
1483     }
1484 
1485     // make a copy of the args which will be expanded in java if required.
1486     nargv = (char **)JLI_MemAlloc(argc * sizeof(char*));
1487     for (i = 0, j = idx; i < argc; i++, j++) {
1488         jboolean arg_expand = (JLI_StrCmp(filteredargs[j].arg, strv[i]) == 0)
1489                                 ? filteredargs[j].has_wildcard
1490                                 : JNI_FALSE;
1491         if (needs_expansion == JNI_FALSE)
1492             needs_expansion = arg_expand;
1493 
1494         // indicator char + String + NULL terminator, the java method will strip
1495         // out the first character, the indicator character, so no matter what
1496         // we add the indicator
1497         tlen = 1 + JLI_StrLen(strv[i]) + 1;
1498         nargv[i] = (char *) JLI_MemAlloc(tlen);
1499         if (JLI_Snprintf(nargv[i], tlen, "%c%s", arg_expand ? 'T' : 'F',
1500                          strv[i]) < 0) {
1501             return NULL;
1502         }
1503         JLI_TraceLauncher("%s\n", nargv[i]);
1504     }
1505 
1506     if (!needs_expansion) {
1507         // clean up any allocated memory and return back the old arguments
1508         for (i = 0 ; i < argc ; i++) {
1509             JLI_MemFree(nargv[i]);
1510         }
1511         JLI_MemFree(nargv);
1512         return NewPlatformStringArray(env, strv, argc);
1513     }
1514     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1515                                                 "expandArgs",
1516                                                 "([Ljava/lang/String;)[Ljava/lang/String;"));
1517 
1518     // expand the arguments that require expansion, the java method will strip
1519     // out the indicator character.
1520     inArray = NewPlatformStringArray(env, nargv, argc);
1521     outArray = (*env)->CallStaticObjectMethod(env, cls, mid, inArray);
1522     for (i = 0; i < argc; i++) {
1523         JLI_MemFree(nargv[i]);
1524     }
1525     JLI_MemFree(nargv);
1526     JLI_MemFree(filteredargs);
1527     return outArray;
1528 }
1529