Path: blob/master/src/java.base/windows/native/libjli/java_md.c
41119 views
/*1* Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425#include <windows.h>26#include <io.h>27#include <process.h>28#include <stdlib.h>29#include <stdio.h>30#include <stdarg.h>31#include <string.h>32#include <sys/types.h>33#include <sys/stat.h>34#include <wtypes.h>35#include <commctrl.h>36#include <assert.h>3738#include <jni.h>39#include "java.h"4041#define JVM_DLL "jvm.dll"42#define JAVA_DLL "java.dll"4344/*45* Prototypes.46*/47static jboolean GetJVMPath(const char *jrepath, const char *jvmtype,48char *jvmpath, jint jvmpathsize);49static jboolean GetJREPath(char *path, jint pathsize);5051#ifdef USE_REGISTRY_LOOKUP52jboolean GetPublicJREHome(char *buf, jint bufsize);53#endif5455/* We supports warmup for UI stack that is performed in parallel56* to VM initialization.57* This helps to improve startup of UI application as warmup phase58* might be long due to initialization of OS or hardware resources.59* It is not CPU bound and therefore it does not interfere with VM init.60* Obviously such warmup only has sense for UI apps and therefore it needs61* to be explicitly requested by passing -Dsun.awt.warmup=true property62* (this is always the case for plugin/javaws).63*64* Implementation launches new thread after VM starts and use it to perform65* warmup code (platform dependent).66* This thread is later reused as AWT toolkit thread as graphics toolkit67* often assume that they are used from the same thread they were launched on.68*69* At the moment we only support warmup for D3D. It only possible on windows70* and only if other flags do not prohibit this (e.g. OpenGL support requested).71*/72#undef ENABLE_AWT_PRELOAD73#ifndef JAVA_ARGS /* turn off AWT preloading for javac, jar, etc */74/* CR6999872: fastdebug crashes if awt library is loaded before JVM is75* initialized*/76#if !defined(DEBUG)77#define ENABLE_AWT_PRELOAD78#endif79#endif8081#ifdef ENABLE_AWT_PRELOAD82/* "AWT was preloaded" flag;83* turned on by AWTPreload().84*/85int awtPreloaded = 0;8687/* Calls a function with the name specified88* the function must be int(*fn)(void).89*/90int AWTPreload(const char *funcName);91/* stops AWT preloading */92void AWTPreloadStop();9394/* D3D preloading */95/* -1: not initialized; 0: OFF, 1: ON */96int awtPreloadD3D = -1;97/* command line parameter to swith D3D preloading on */98#define PARAM_PRELOAD_D3D "-Dsun.awt.warmup"99/* D3D/OpenGL management parameters */100#define PARAM_NODDRAW "-Dsun.java2d.noddraw"101#define PARAM_D3D "-Dsun.java2d.d3d"102#define PARAM_OPENGL "-Dsun.java2d.opengl"103/* funtion in awt.dll (src/windows/native/sun/java2d/d3d/D3DPipelineManager.cpp) */104#define D3D_PRELOAD_FUNC "preloadD3D"105106/* Extracts value of a parameter with the specified name107* from command line argument (returns pointer in the argument).108* Returns NULL if the argument does not contains the parameter.109* e.g.:110* GetParamValue("theParam", "theParam=value") returns pointer to "value".111*/112const char * GetParamValue(const char *paramName, const char *arg) {113size_t nameLen = JLI_StrLen(paramName);114if (JLI_StrNCmp(paramName, arg, nameLen) == 0) {115/* arg[nameLen] is valid (may contain final NULL) */116if (arg[nameLen] == '=') {117return arg + nameLen + 1;118}119}120return NULL;121}122123/* Checks if commandline argument contains property specified124* and analyze it as boolean property (true/false).125* Returns -1 if the argument does not contain the parameter;126* Returns 1 if the argument contains the parameter and its value is "true";127* Returns 0 if the argument contains the parameter and its value is "false".128*/129int GetBoolParamValue(const char *paramName, const char *arg) {130const char * paramValue = GetParamValue(paramName, arg);131if (paramValue != NULL) {132if (JLI_StrCaseCmp(paramValue, "true") == 0) {133return 1;134}135if (JLI_StrCaseCmp(paramValue, "false") == 0) {136return 0;137}138}139return -1;140}141#endif /* ENABLE_AWT_PRELOAD */142143144static jboolean _isjavaw = JNI_FALSE;145146147jboolean148IsJavaw()149{150return _isjavaw;151}152153/*154*155*/156void157CreateExecutionEnvironment(int *pargc, char ***pargv,158char *jrepath, jint so_jrepath,159char *jvmpath, jint so_jvmpath,160char *jvmcfg, jint so_jvmcfg) {161162char *jvmtype;163int i = 0;164char** argv = *pargv;165166/* Find out where the JRE is that we will be using. */167if (!GetJREPath(jrepath, so_jrepath)) {168JLI_ReportErrorMessage(JRE_ERROR1);169exit(2);170}171172JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%sjvm.cfg",173jrepath, FILESEP, FILESEP);174175/* Find the specified JVM type */176if (ReadKnownVMs(jvmcfg, JNI_FALSE) < 1) {177JLI_ReportErrorMessage(CFG_ERROR7);178exit(1);179}180181jvmtype = CheckJvmType(pargc, pargv, JNI_FALSE);182if (JLI_StrCmp(jvmtype, "ERROR") == 0) {183JLI_ReportErrorMessage(CFG_ERROR9);184exit(4);185}186187jvmpath[0] = '\0';188if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath)) {189JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath);190exit(4);191}192/* If we got here, jvmpath has been correctly initialized. */193194/* Check if we need preload AWT */195#ifdef ENABLE_AWT_PRELOAD196argv = *pargv;197for (i = 0; i < *pargc ; i++) {198/* Tests the "turn on" parameter only if not set yet. */199if (awtPreloadD3D < 0) {200if (GetBoolParamValue(PARAM_PRELOAD_D3D, argv[i]) == 1) {201awtPreloadD3D = 1;202}203}204/* Test parameters which can disable preloading if not already disabled. */205if (awtPreloadD3D != 0) {206if (GetBoolParamValue(PARAM_NODDRAW, argv[i]) == 1207|| GetBoolParamValue(PARAM_D3D, argv[i]) == 0208|| GetBoolParamValue(PARAM_OPENGL, argv[i]) == 1)209{210awtPreloadD3D = 0;211/* no need to test the rest of the parameters */212break;213}214}215}216#endif /* ENABLE_AWT_PRELOAD */217}218219220static jboolean221LoadMSVCRT()222{223// Only do this once224static int loaded = 0;225char crtpath[MAXPATHLEN];226227if (!loaded) {228/*229* The Microsoft C Runtime Library needs to be loaded first. A copy is230* assumed to be present in the "JRE path" directory. If it is not found231* there (or "JRE path" fails to resolve), skip the explicit load and let232* nature take its course, which is likely to be a failure to execute.233* The makefiles will provide the correct lib contained in quotes in the234* macro MSVCR_DLL_NAME.235*/236#ifdef MSVCR_DLL_NAME237if (GetJREPath(crtpath, MAXPATHLEN)) {238if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") +239JLI_StrLen(MSVCR_DLL_NAME) >= MAXPATHLEN) {240JLI_ReportErrorMessage(JRE_ERROR11);241return JNI_FALSE;242}243(void)JLI_StrCat(crtpath, "\\bin\\" MSVCR_DLL_NAME); /* Add crt dll */244JLI_TraceLauncher("CRT path is %s\n", crtpath);245if (_access(crtpath, 0) == 0) {246if (LoadLibrary(crtpath) == 0) {247JLI_ReportErrorMessage(DLL_ERROR4, crtpath);248return JNI_FALSE;249}250}251}252#endif /* MSVCR_DLL_NAME */253#ifdef VCRUNTIME_1_DLL_NAME254if (GetJREPath(crtpath, MAXPATHLEN)) {255if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") +256JLI_StrLen(VCRUNTIME_1_DLL_NAME) >= MAXPATHLEN) {257JLI_ReportErrorMessage(JRE_ERROR11);258return JNI_FALSE;259}260(void)JLI_StrCat(crtpath, "\\bin\\" VCRUNTIME_1_DLL_NAME); /* Add crt dll */261JLI_TraceLauncher("CRT path is %s\n", crtpath);262if (_access(crtpath, 0) == 0) {263if (LoadLibrary(crtpath) == 0) {264JLI_ReportErrorMessage(DLL_ERROR4, crtpath);265return JNI_FALSE;266}267}268}269#endif /* VCRUNTIME_1_DLL_NAME */270#ifdef MSVCP_DLL_NAME271if (GetJREPath(crtpath, MAXPATHLEN)) {272if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") +273JLI_StrLen(MSVCP_DLL_NAME) >= MAXPATHLEN) {274JLI_ReportErrorMessage(JRE_ERROR11);275return JNI_FALSE;276}277(void)JLI_StrCat(crtpath, "\\bin\\" MSVCP_DLL_NAME); /* Add prt dll */278JLI_TraceLauncher("PRT path is %s\n", crtpath);279if (_access(crtpath, 0) == 0) {280if (LoadLibrary(crtpath) == 0) {281JLI_ReportErrorMessage(DLL_ERROR4, crtpath);282return JNI_FALSE;283}284}285}286#endif /* MSVCP_DLL_NAME */287loaded = 1;288}289return JNI_TRUE;290}291292293/*294* Find path to JRE based on .exe's location or registry settings.295*/296jboolean297GetJREPath(char *path, jint pathsize)298{299char javadll[MAXPATHLEN];300struct stat s;301302if (GetApplicationHome(path, pathsize)) {303/* Is JRE co-located with the application? */304JLI_Snprintf(javadll, sizeof(javadll), "%s\\bin\\" JAVA_DLL, path);305if (stat(javadll, &s) == 0) {306JLI_TraceLauncher("JRE path is %s\n", path);307return JNI_TRUE;308}309/* ensure storage for path + \jre + NULL */310if ((JLI_StrLen(path) + 4 + 1) > (size_t) pathsize) {311JLI_TraceLauncher("Insufficient space to store JRE path\n");312return JNI_FALSE;313}314/* Does this app ship a private JRE in <apphome>\jre directory? */315JLI_Snprintf(javadll, sizeof (javadll), "%s\\jre\\bin\\" JAVA_DLL, path);316if (stat(javadll, &s) == 0) {317JLI_StrCat(path, "\\jre");318JLI_TraceLauncher("JRE path is %s\n", path);319return JNI_TRUE;320}321}322323/* Try getting path to JRE from path to JLI.DLL */324if (GetApplicationHomeFromDll(path, pathsize)) {325JLI_Snprintf(javadll, sizeof(javadll), "%s\\bin\\" JAVA_DLL, path);326if (stat(javadll, &s) == 0) {327JLI_TraceLauncher("JRE path is %s\n", path);328return JNI_TRUE;329}330}331332#ifdef USE_REGISTRY_LOOKUP333/* Lookup public JRE using Windows registry. */334if (GetPublicJREHome(path, pathsize)) {335JLI_TraceLauncher("JRE path is %s\n", path);336return JNI_TRUE;337}338#endif339340JLI_ReportErrorMessage(JRE_ERROR8 JAVA_DLL);341return JNI_FALSE;342}343344/*345* Given a JRE location and a JVM type, construct what the name the346* JVM shared library will be. Return true, if such a library347* exists, false otherwise.348*/349static jboolean350GetJVMPath(const char *jrepath, const char *jvmtype,351char *jvmpath, jint jvmpathsize)352{353struct stat s;354if (JLI_StrChr(jvmtype, '/') || JLI_StrChr(jvmtype, '\\')) {355JLI_Snprintf(jvmpath, jvmpathsize, "%s\\" JVM_DLL, jvmtype);356} else {357JLI_Snprintf(jvmpath, jvmpathsize, "%s\\bin\\%s\\" JVM_DLL,358jrepath, jvmtype);359}360if (stat(jvmpath, &s) == 0) {361return JNI_TRUE;362} else {363return JNI_FALSE;364}365}366367/*368* Load a jvm from "jvmpath" and initialize the invocation functions.369*/370jboolean371LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)372{373HINSTANCE handle;374375JLI_TraceLauncher("JVM path is %s\n", jvmpath);376377/*378* The Microsoft C Runtime Library needs to be loaded first. A copy is379* assumed to be present in the "JRE path" directory. If it is not found380* there (or "JRE path" fails to resolve), skip the explicit load and let381* nature take its course, which is likely to be a failure to execute.382*383*/384LoadMSVCRT();385386/* Load the Java VM DLL */387if ((handle = LoadLibrary(jvmpath)) == 0) {388JLI_ReportErrorMessage(DLL_ERROR4, (char *)jvmpath);389return JNI_FALSE;390}391392/* Now get the function addresses */393ifn->CreateJavaVM =394(void *)GetProcAddress(handle, "JNI_CreateJavaVM");395ifn->GetDefaultJavaVMInitArgs =396(void *)GetProcAddress(handle, "JNI_GetDefaultJavaVMInitArgs");397if (ifn->CreateJavaVM == 0 || ifn->GetDefaultJavaVMInitArgs == 0) {398JLI_ReportErrorMessage(JNI_ERROR1, (char *)jvmpath);399return JNI_FALSE;400}401402return JNI_TRUE;403}404405/*406* Removes the trailing file name and one sub-folder from a path.407* If buf is "c:\foo\bin\javac", then put "c:\foo" into buf.408*/409jboolean410TruncatePath(char *buf)411{412char *cp;413*JLI_StrRChr(buf, '\\') = '\0'; /* remove .exe file name */414if ((cp = JLI_StrRChr(buf, '\\')) == 0) {415/* This happens if the application is in a drive root, and416* there is no bin directory. */417buf[0] = '\0';418return JNI_FALSE;419}420*cp = '\0'; /* remove the bin\ part */421return JNI_TRUE;422}423424/*425* Retrieves the path to the JRE home by locating the executable file426* of the current process and then truncating the path to the executable427*/428jboolean429GetApplicationHome(char *buf, jint bufsize)430{431GetModuleFileName(NULL, buf, bufsize);432return TruncatePath(buf);433}434435/*436* Retrieves the path to the JRE home by locating JLI.DLL and437* then truncating the path to JLI.DLL438*/439jboolean440GetApplicationHomeFromDll(char *buf, jint bufsize)441{442HMODULE module;443DWORD flags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |444GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT;445446if (GetModuleHandleEx(flags, (LPCSTR)&GetJREPath, &module) != 0) {447if (GetModuleFileName(module, buf, bufsize) != 0) {448return TruncatePath(buf);449}450}451return JNI_FALSE;452}453454/*455* Support for doing cheap, accurate interval timing.456*/457static jboolean counterAvailable = JNI_FALSE;458static jboolean counterInitialized = JNI_FALSE;459static LARGE_INTEGER counterFrequency;460461jlong CurrentTimeMicros()462{463LARGE_INTEGER count;464465if (!counterInitialized) {466counterAvailable = QueryPerformanceFrequency(&counterFrequency);467counterInitialized = JNI_TRUE;468}469if (!counterAvailable) {470return 0;471}472QueryPerformanceCounter(&count);473474return (jlong)(count.QuadPart * 1000 * 1000 / counterFrequency.QuadPart);475}476477/*478* windows snprintf does not guarantee a null terminator in the buffer,479* if the computed size is equal to or greater than the buffer size,480* as well as error conditions. This function guarantees a null terminator481* under all these conditions. An unreasonable buffer or size will return482* an error value. Under all other conditions this function will return the483* size of the bytes actually written minus the null terminator, similar484* to ansi snprintf api. Thus when calling this function the caller must485* ensure storage for the null terminator.486*/487int488JLI_Snprintf(char* buffer, size_t size, const char* format, ...) {489int rc;490va_list vl;491if (size == 0 || buffer == NULL)492return -1;493buffer[0] = '\0';494va_start(vl, format);495rc = vsnprintf(buffer, size, format, vl);496va_end(vl);497/* force a null terminator, if something is amiss */498if (rc < 0) {499/* apply ansi semantics */500buffer[size - 1] = '\0';501return (int)size;502} else if (rc == size) {503/* force a null terminator */504buffer[size - 1] = '\0';505}506return rc;507}508509static errno_t convert_to_unicode(const char* path, const wchar_t* prefix, wchar_t** wpath) {510int unicode_path_len;511size_t prefix_len, wpath_len;512513/*514* Get required buffer size to convert to Unicode.515* The return value includes the terminating null character.516*/517unicode_path_len = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS,518path, -1, NULL, 0);519if (unicode_path_len == 0) {520return EINVAL;521}522523prefix_len = wcslen(prefix);524wpath_len = prefix_len + unicode_path_len;525*wpath = (wchar_t*)JLI_MemAlloc(wpath_len * sizeof(wchar_t));526if (*wpath == NULL) {527return ENOMEM;528}529530wcsncpy(*wpath, prefix, prefix_len);531if (MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS,532path, -1, &((*wpath)[prefix_len]), (int)wpath_len) == 0) {533JLI_MemFree(*wpath);534*wpath = NULL;535return EINVAL;536}537538return ERROR_SUCCESS;539}540541/* taken from hotspot and slightly adjusted for jli lib;542* creates a UNC/ELP path from input 'path'543* the return buffer is allocated in C heap and needs to be freed using544* JLI_MemFree by the caller.545*/546static wchar_t* create_unc_path(const char* path, errno_t* err) {547wchar_t* wpath = NULL;548size_t converted_chars = 0;549size_t path_len = strlen(path) + 1; /* includes the terminating NULL */550if (path[0] == '\\' && path[1] == '\\') {551if (path[2] == '?' && path[3] == '\\') {552/* if it already has a \\?\ don't do the prefix */553*err = convert_to_unicode(path, L"", &wpath);554} else {555/* only UNC pathname includes double slashes here */556*err = convert_to_unicode(path, L"\\\\?\\UNC", &wpath);557}558} else {559*err = convert_to_unicode(path, L"\\\\?\\", &wpath);560}561return wpath;562}563564int JLI_Open(const char* name, int flags) {565int fd;566if (strlen(name) < MAX_PATH) {567fd = _open(name, flags);568} else {569errno_t err = ERROR_SUCCESS;570wchar_t* wpath = create_unc_path(name, &err);571if (err != ERROR_SUCCESS) {572if (wpath != NULL) JLI_MemFree(wpath);573errno = err;574return -1;575}576fd = _wopen(wpath, flags);577if (fd == -1) {578errno = GetLastError();579}580JLI_MemFree(wpath);581}582return fd;583}584585JNIEXPORT void JNICALL586JLI_ReportErrorMessage(const char* fmt, ...) {587va_list vl;588va_start(vl,fmt);589590if (IsJavaw()) {591char *message;592593/* get the length of the string we need */594int n = _vscprintf(fmt, vl);595596message = (char *)JLI_MemAlloc(n + 1);597_vsnprintf(message, n, fmt, vl);598message[n]='\0';599MessageBox(NULL, message, "Java Virtual Machine Launcher",600(MB_OK|MB_ICONSTOP|MB_APPLMODAL));601JLI_MemFree(message);602} else {603vfprintf(stderr, fmt, vl);604fprintf(stderr, "\n");605}606va_end(vl);607}608609/*610* Just like JLI_ReportErrorMessage, except that it concatenates the system611* error message if any, its upto the calling routine to correctly612* format the separation of the messages.613*/614JNIEXPORT void JNICALL615JLI_ReportErrorMessageSys(const char *fmt, ...)616{617va_list vl;618619int save_errno = errno;620DWORD errval;621jboolean freeit = JNI_FALSE;622char *errtext = NULL;623624va_start(vl, fmt);625626if ((errval = GetLastError()) != 0) { /* Platform SDK / DOS Error */627int n = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|628FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_ALLOCATE_BUFFER,629NULL, errval, 0, (LPTSTR)&errtext, 0, NULL);630if (errtext == NULL || n == 0) { /* Paranoia check */631errtext = "";632n = 0;633} else {634freeit = JNI_TRUE;635if (n > 2) { /* Drop final CR, LF */636if (errtext[n - 1] == '\n') n--;637if (errtext[n - 1] == '\r') n--;638errtext[n] = '\0';639}640}641} else { /* C runtime error that has no corresponding DOS error code */642errtext = strerror(save_errno);643}644645if (IsJavaw()) {646char *message;647int mlen;648/* get the length of the string we need */649int len = mlen = _vscprintf(fmt, vl) + 1;650if (freeit) {651mlen += (int)JLI_StrLen(errtext);652}653654message = (char *)JLI_MemAlloc(mlen);655_vsnprintf(message, len, fmt, vl);656message[len]='\0';657658if (freeit) {659JLI_StrCat(message, errtext);660}661662MessageBox(NULL, message, "Java Virtual Machine Launcher",663(MB_OK|MB_ICONSTOP|MB_APPLMODAL));664665JLI_MemFree(message);666} else {667vfprintf(stderr, fmt, vl);668if (freeit) {669fprintf(stderr, "%s", errtext);670}671}672if (freeit) {673(void)LocalFree((HLOCAL)errtext);674}675va_end(vl);676}677678JNIEXPORT void JNICALL679JLI_ReportExceptionDescription(JNIEnv * env) {680if (IsJavaw()) {681/*682* This code should be replaced by code which opens a window with683* the exception detail message, for now atleast put a dialog up.684*/685MessageBox(NULL, "A Java Exception has occurred.", "Java Virtual Machine Launcher",686(MB_OK|MB_ICONSTOP|MB_APPLMODAL));687} else {688(*env)->ExceptionDescribe(env);689}690}691692/*693* Wrapper for platform dependent unsetenv function.694*/695int696UnsetEnv(char *name)697{698int ret;699char *buf = JLI_MemAlloc(JLI_StrLen(name) + 2);700buf = JLI_StrCat(JLI_StrCpy(buf, name), "=");701ret = _putenv(buf);702JLI_MemFree(buf);703return (ret);704}705706/* --- Splash Screen shared library support --- */707708static const char* SPLASHSCREEN_SO = "\\bin\\splashscreen.dll";709710static HMODULE hSplashLib = NULL;711712void* SplashProcAddress(const char* name) {713char libraryPath[MAXPATHLEN]; /* some extra space for JLI_StrCat'ing SPLASHSCREEN_SO */714715if (!GetJREPath(libraryPath, MAXPATHLEN)) {716return NULL;717}718if (JLI_StrLen(libraryPath)+JLI_StrLen(SPLASHSCREEN_SO) >= MAXPATHLEN) {719return NULL;720}721JLI_StrCat(libraryPath, SPLASHSCREEN_SO);722723if (!hSplashLib) {724hSplashLib = LoadLibrary(libraryPath);725}726if (hSplashLib) {727return GetProcAddress(hSplashLib, name);728} else {729return NULL;730}731}732733/*734* Signature adapter for _beginthreadex().735*/736static unsigned __stdcall ThreadJavaMain(void* args) {737return (unsigned)JavaMain(args);738}739740/*741* Block current thread and continue execution in a new thread.742*/743int744CallJavaMainInNewThread(jlong stack_size, void* args) {745int rslt = 0;746unsigned thread_id;747748#ifndef STACK_SIZE_PARAM_IS_A_RESERVATION749#define STACK_SIZE_PARAM_IS_A_RESERVATION (0x10000)750#endif751752/*753* STACK_SIZE_PARAM_IS_A_RESERVATION is what we want, but it's not754* supported on older version of Windows. Try first with the flag; and755* if that fails try again without the flag. See MSDN document or HotSpot756* source (os_win32.cpp) for details.757*/758HANDLE thread_handle =759(HANDLE)_beginthreadex(NULL,760(unsigned)stack_size,761ThreadJavaMain,762args,763STACK_SIZE_PARAM_IS_A_RESERVATION,764&thread_id);765if (thread_handle == NULL) {766thread_handle =767(HANDLE)_beginthreadex(NULL,768(unsigned)stack_size,769ThreadJavaMain,770args,7710,772&thread_id);773}774775/* AWT preloading (AFTER main thread start) */776#ifdef ENABLE_AWT_PRELOAD777/* D3D preloading */778if (awtPreloadD3D != 0) {779char *envValue;780/* D3D routines checks env.var J2D_D3D if no appropriate781* command line params was specified782*/783envValue = getenv("J2D_D3D");784if (envValue != NULL && JLI_StrCaseCmp(envValue, "false") == 0) {785awtPreloadD3D = 0;786}787/* Test that AWT preloading isn't disabled by J2D_D3D_PRELOAD env.var */788envValue = getenv("J2D_D3D_PRELOAD");789if (envValue != NULL && JLI_StrCaseCmp(envValue, "false") == 0) {790awtPreloadD3D = 0;791}792if (awtPreloadD3D < 0) {793/* If awtPreloadD3D is still undefined (-1), test794* if it is turned on by J2D_D3D_PRELOAD env.var.795* By default it's turned OFF.796*/797awtPreloadD3D = 0;798if (envValue != NULL && JLI_StrCaseCmp(envValue, "true") == 0) {799awtPreloadD3D = 1;800}801}802}803if (awtPreloadD3D) {804AWTPreload(D3D_PRELOAD_FUNC);805}806#endif /* ENABLE_AWT_PRELOAD */807808if (thread_handle) {809WaitForSingleObject(thread_handle, INFINITE);810GetExitCodeThread(thread_handle, &rslt);811CloseHandle(thread_handle);812} else {813rslt = JavaMain(args);814}815816#ifdef ENABLE_AWT_PRELOAD817if (awtPreloaded) {818AWTPreloadStop();819}820#endif /* ENABLE_AWT_PRELOAD */821822return rslt;823}824825/*826* The implementation for finding classes from the bootstrap827* class loader, refer to java.h828*/829static FindClassFromBootLoader_t *findBootClass = NULL;830831jclass FindBootStrapClass(JNIEnv *env, const char *classname)832{833HMODULE hJvm;834835if (findBootClass == NULL) {836hJvm = GetModuleHandle(JVM_DLL);837if (hJvm == NULL) return NULL;838/* need to use the demangled entry point */839findBootClass = (FindClassFromBootLoader_t *)GetProcAddress(hJvm,840"JVM_FindClassFromBootLoader");841if (findBootClass == NULL) {842JLI_ReportErrorMessage(DLL_ERROR4, "JVM_FindClassFromBootLoader");843return NULL;844}845}846return findBootClass(env, classname);847}848849void850InitLauncher(boolean javaw)851{852INITCOMMONCONTROLSEX icx;853854/*855* Required for javaw mode MessageBox output as well as for856* HotSpot -XX:+ShowMessageBoxOnError in java mode, an empty857* flag field is sufficient to perform the basic UI initialization.858*/859memset(&icx, 0, sizeof(INITCOMMONCONTROLSEX));860icx.dwSize = sizeof(INITCOMMONCONTROLSEX);861InitCommonControlsEx(&icx);862_isjavaw = javaw;863JLI_SetTraceLauncher();864}865866867/* ============================== */868/* AWT preloading */869#ifdef ENABLE_AWT_PRELOAD870871typedef int FnPreloadStart(void);872typedef void FnPreloadStop(void);873static FnPreloadStop *fnPreloadStop = NULL;874static HMODULE hPreloadAwt = NULL;875876/*877* Starts AWT preloading878*/879int AWTPreload(const char *funcName)880{881int result = -1;882/* load AWT library once (if several preload function should be called) */883if (hPreloadAwt == NULL) {884/* awt.dll is not loaded yet */885char libraryPath[MAXPATHLEN];886size_t jrePathLen = 0;887HMODULE hJava = NULL;888HMODULE hVerify = NULL;889890while (1) {891/* awt.dll depends on jvm.dll & java.dll;892* jvm.dll is already loaded, so we need only java.dll;893* java.dll depends on MSVCRT lib & verify.dll.894*/895if (!GetJREPath(libraryPath, MAXPATHLEN)) {896break;897}898899/* save path length */900jrePathLen = JLI_StrLen(libraryPath);901902if (jrePathLen + JLI_StrLen("\\bin\\verify.dll") >= MAXPATHLEN) {903/* jre path is too long, the library path will not fit there;904* report and abort preloading905*/906JLI_ReportErrorMessage(JRE_ERROR11);907break;908}909910/* load msvcrt 1st */911LoadMSVCRT();912913/* load verify.dll */914JLI_StrCat(libraryPath, "\\bin\\verify.dll");915hVerify = LoadLibrary(libraryPath);916if (hVerify == NULL) {917break;918}919920/* restore jrePath */921libraryPath[jrePathLen] = 0;922/* load java.dll */923JLI_StrCat(libraryPath, "\\bin\\" JAVA_DLL);924hJava = LoadLibrary(libraryPath);925if (hJava == NULL) {926break;927}928929/* restore jrePath */930libraryPath[jrePathLen] = 0;931/* load awt.dll */932JLI_StrCat(libraryPath, "\\bin\\awt.dll");933hPreloadAwt = LoadLibrary(libraryPath);934if (hPreloadAwt == NULL) {935break;936}937938/* get "preloadStop" func ptr */939fnPreloadStop = (FnPreloadStop *)GetProcAddress(hPreloadAwt, "preloadStop");940941break;942}943}944945if (hPreloadAwt != NULL) {946FnPreloadStart *fnInit = (FnPreloadStart *)GetProcAddress(hPreloadAwt, funcName);947if (fnInit != NULL) {948/* don't forget to stop preloading */949awtPreloaded = 1;950951result = fnInit();952}953}954955return result;956}957958/*959* Terminates AWT preloading960*/961void AWTPreloadStop() {962if (fnPreloadStop != NULL) {963fnPreloadStop();964}965}966967#endif /* ENABLE_AWT_PRELOAD */968969int970JVMInit(InvocationFunctions* ifn, jlong threadStackSize,971int argc, char **argv,972int mode, char *what, int ret)973{974ShowSplashScreen();975return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret);976}977978void979PostJVMInit(JNIEnv *env, jclass mainClass, JavaVM *vm)980{981// stubbed out for windows and *nixes.982}983984void985RegisterThread()986{987// stubbed out for windows and *nixes.988}989990/*991* on windows, we return a false to indicate this option is not applicable992*/993jboolean994ProcessPlatformOption(const char *arg)995{996return JNI_FALSE;997}998999/*1000* At this point we have the arguments to the application, and we need to1001* check with original stdargs in order to compare which of these truly1002* needs expansion. cmdtoargs will specify this if it finds a bare1003* (unquoted) argument containing a glob character(s) ie. * or ?1004*/1005jobjectArray1006CreateApplicationArgs(JNIEnv *env, char **strv, int argc)1007{1008int i, j, idx;1009size_t tlen;1010jobjectArray outArray, inArray;1011char *arg, **nargv;1012jboolean needs_expansion = JNI_FALSE;1013jmethodID mid;1014int stdargc;1015StdArg *stdargs;1016int *appArgIdx;1017int isTool;1018jclass cls = GetLauncherHelperClass(env);1019NULL_CHECK0(cls);10201021if (argc == 0) {1022return NewPlatformStringArray(env, strv, argc);1023}1024// the holy grail we need to compare with.1025stdargs = JLI_GetStdArgs();1026stdargc = JLI_GetStdArgc();10271028// sanity check, this should never happen1029if (argc > stdargc) {1030JLI_TraceLauncher("Warning: app args is larger than the original, %d %d\n", argc, stdargc);1031JLI_TraceLauncher("passing arguments as-is.\n");1032return NewPlatformStringArray(env, strv, argc);1033}10341035// sanity check, match the args we have, to the holy grail1036idx = JLI_GetAppArgIndex();10371038// First arg index is NOT_FOUND1039if (idx < 0) {1040// The only allowed value should be NOT_FOUND (-1) unless another change introduces1041// a different negative index1042assert (idx == -1);1043JLI_TraceLauncher("Warning: first app arg index not found, %d\n", idx);1044JLI_TraceLauncher("passing arguments as-is.\n");1045return NewPlatformStringArray(env, strv, argc);1046}10471048isTool = (idx == 0);1049if (isTool) { idx++; } // skip tool name1050JLI_TraceLauncher("AppArgIndex: %d points to %s\n", idx, stdargs[idx].arg);10511052appArgIdx = calloc(argc, sizeof(int));1053for (i = idx, j = 0; i < stdargc; i++) {1054if (isTool) { // filter -J used by tools to pass JVM options1055arg = stdargs[i].arg;1056if (arg[0] == '-' && arg[1] == 'J') {1057continue;1058}1059}1060appArgIdx[j++] = i;1061}1062// sanity check, ensure same number of arguments for application1063if (j != argc) {1064JLI_TraceLauncher("Warning: app args count doesn't match, %d %d\n", j, argc);1065JLI_TraceLauncher("passing arguments as-is.\n");1066JLI_MemFree(appArgIdx);1067return NewPlatformStringArray(env, strv, argc);1068}10691070// make a copy of the args which will be expanded in java if required.1071nargv = (char **)JLI_MemAlloc(argc * sizeof(char*));1072for (i = 0; i < argc; i++) {1073jboolean arg_expand;1074j = appArgIdx[i];1075arg_expand = (JLI_StrCmp(stdargs[j].arg, strv[i]) == 0)1076? stdargs[j].has_wildcard1077: JNI_FALSE;1078if (needs_expansion == JNI_FALSE)1079needs_expansion = arg_expand;10801081// indicator char + String + NULL terminator, the java method will strip1082// out the first character, the indicator character, so no matter what1083// we add the indicator1084tlen = 1 + JLI_StrLen(strv[i]) + 1;1085nargv[i] = (char *) JLI_MemAlloc(tlen);1086if (JLI_Snprintf(nargv[i], tlen, "%c%s", arg_expand ? 'T' : 'F',1087strv[i]) < 0) {1088return NULL;1089}1090JLI_TraceLauncher("%s\n", nargv[i]);1091}10921093if (!needs_expansion) {1094// clean up any allocated memory and return back the old arguments1095for (i = 0 ; i < argc ; i++) {1096JLI_MemFree(nargv[i]);1097}1098JLI_MemFree(nargv);1099JLI_MemFree(appArgIdx);1100return NewPlatformStringArray(env, strv, argc);1101}1102NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,1103"expandArgs",1104"([Ljava/lang/String;)[Ljava/lang/String;"));11051106// expand the arguments that require expansion, the java method will strip1107// out the indicator character.1108NULL_CHECK0(inArray = NewPlatformStringArray(env, nargv, argc));1109outArray = (*env)->CallStaticObjectMethod(env, cls, mid, inArray);1110for (i = 0; i < argc; i++) {1111JLI_MemFree(nargv[i]);1112}1113JLI_MemFree(nargv);1114JLI_MemFree(appArgIdx);1115return outArray;1116}111711181119