src/os/windows/launcher/java_md.c

Wed, 15 Dec 2010 07:11:31 -0800

author
sla
date
Wed, 15 Dec 2010 07:11:31 -0800
changeset 2369
aa6e219afbf1
parent 2327
cb2d0a362639
child 4465
203f64878aab
permissions
-rw-r--r--

7006354: Updates to Visual Studio project creation and development launcher
Summary: Updates to Visual Studio project creation and development launcher
Reviewed-by: stefank, coleenp

     1 /*
     2  * Copyright (c) 1999, 2010, 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.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 #include <ctype.h>
    26 #include <windows.h>
    27 #include <io.h>
    28 #include <process.h>
    29 #include <stdlib.h>
    30 #include <stdio.h>
    31 #include <string.h>
    32 #include <sys/types.h>
    33 #include <sys/stat.h>
    35 #include <jni.h>
    36 #include "java.h"
    37 #ifndef GAMMA
    38 #include "version_comp.h"
    39 #endif
    41 #define JVM_DLL "jvm.dll"
    42 #define JAVA_DLL "java.dll"
    43 #define CRT_DLL "msvcr71.dll"
    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 static void EnsureJreInstallation(const char *jrepath);
    54 /* We supports warmup for UI stack that is performed in parallel
    55  * to VM initialization.
    56  * This helps to improve startup of UI application as warmup phase
    57  * might be long due to initialization of OS or hardware resources.
    58  * It is not CPU bound and therefore it does not interfere with VM init.
    59  * Obviously such warmup only has sense for UI apps and therefore it needs
    60  * to be explicitly requested by passing -Dsun.awt.warmup=true property
    61  * (this is always the case for plugin/javaws).
    62  *
    63  * Implementation launches new thread after VM starts and use it to perform
    64  * warmup code (platform dependent).
    65  * This thread is later reused as AWT toolkit thread as graphics toolkit
    66  * often assume that they are used from the same thread they were launched on.
    67  *
    68  * At the moment we only support warmup for D3D. It only possible on windows
    69  * and only if other flags do not prohibit this (e.g. OpenGL support requested).
    70  */
    71 #undef ENABLE_AWT_PRELOAD
    72 #ifndef JAVA_ARGS /* turn off AWT preloading for javac, jar, etc */
    73   #ifdef _X86_ /* for now disable AWT preloading for 64bit */
    74     #define ENABLE_AWT_PRELOAD
    75   #endif
    76 #endif
    78 #ifdef ENABLE_AWT_PRELOAD
    79 /* "AWT was preloaded" flag;
    80  * Turned on by AWTPreload().
    81  */
    82 int awtPreloaded = 0;
    84 /* Calls a function with the name specified.
    85  * The function must be int(*fn)(void).
    86  */
    87 int AWTPreload(const char *funcName);
    88 /* Stops AWT preloading. */
    89 void AWTPreloadStop();
    91 /* D3D preloading */
    92 /* -1: not initialized; 0: OFF, 1: ON */
    93 int awtPreloadD3D = -1;
    94 /* Command line parameter to swith D3D preloading on. */
    95 #define PARAM_PRELOAD_D3D "-Dsun.awt.warmup"
    96 /* D3D/OpenGL management parameters (may disable D3D preloading) */
    97 #define PARAM_NODDRAW "-Dsun.java2d.noddraw"
    98 #define PARAM_D3D "-Dsun.java2d.d3d"
    99 #define PARAM_OPENGL "-Dsun.java2d.opengl"
   100 /* funtion in awt.dll (src/windows/native/sun/java2d/d3d/D3DPipelineManager.cpp) */
   101 #define D3D_PRELOAD_FUNC "preloadD3D"
   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  */
   110 const char * GetParamValue(const char *paramName, const char *arg) {
   111     int nameLen = strlen(paramName);
   112     if (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 }
   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  */
   127 int GetBoolParamValue(const char *paramName, const char *arg) {
   128     const char * paramValue = GetParamValue(paramName, arg);
   129     if (paramValue != NULL) {
   130         if (stricmp(paramValue, "true") == 0) {
   131             return 1;
   132         }
   133         if (stricmp(paramValue, "false") == 0) {
   134             return 0;
   135         }
   136     }
   137     return -1;
   138 }
   139 #endif /* ENABLE_AWT_PRELOAD */
   142 const char *
   143 GetArch()
   144 {
   146 #ifdef _M_AMD64
   147     return "amd64";
   148 #elif defined(_M_IA64)
   149     return "ia64";
   150 #else
   151     return "i386";
   152 #endif
   153 }
   155 /*
   156  *
   157  */
   158 void
   159 CreateExecutionEnvironment(int *_argc,
   160                            char ***_argv,
   161                            char jrepath[],
   162                            jint so_jrepath,
   163                            char jvmpath[],
   164                            jint so_jvmpath,
   165                            char **original_argv) {
   166 #ifndef GAMMA
   167    char * jvmtype;
   169     /* Find out where the JRE is that we will be using. */
   170     if (!GetJREPath(jrepath, so_jrepath)) {
   171         ReportErrorMessage("Error: could not find Java SE Runtime Environment.",
   172                            JNI_TRUE);
   173         exit(2);
   174     }
   176     /* Do this before we read jvm.cfg */
   177     EnsureJreInstallation(jrepath);
   179     /* Find the specified JVM type */
   180     if (ReadKnownVMs(jrepath, (char*)GetArch(), JNI_FALSE) < 1) {
   181         ReportErrorMessage("Error: no known VMs. (check for corrupt jvm.cfg file)",
   182                            JNI_TRUE);
   183         exit(1);
   184     }
   185     jvmtype = CheckJvmType(_argc, _argv, JNI_FALSE);
   187     jvmpath[0] = '\0';
   188     if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath)) {
   189         char * message=NULL;
   190         const char * format = "Error: no `%s' JVM at `%s'.";
   191         message = (char *)JLI_MemAlloc((strlen(format)+strlen(jvmtype)+
   192                                     strlen(jvmpath)) * sizeof(char));
   193         sprintf(message,format, jvmtype, jvmpath);
   194         ReportErrorMessage(message, JNI_TRUE);
   195         exit(4);
   196     }
   197     /* If we got here, jvmpath has been correctly initialized. */
   199 #else  /* ifndef GAMMA */
   201     /*
   202      * gamma launcher is simpler in that it doesn't handle VM flavors, data
   203      * model, etc. Assuming everything is set-up correctly
   204      * all we need to do here is to return correct path names. See also
   205      * GetJVMPath() and GetApplicationHome().
   206      */
   208   {
   209     if (!GetJREPath(jrepath, so_jrepath) ) {
   210        ReportErrorMessage("Error: could not find Java SE Runtime Environment.",
   211                           JNI_TRUE);
   212        exit(2);
   213     }
   215     if (!GetJVMPath(jrepath, NULL, jvmpath, so_jvmpath)) {
   216        char * message=NULL;
   217        const char * format = "Error: no JVM at `%s'.";
   218        message = (char *)JLI_MemAlloc((strlen(format)+
   219                                        strlen(jvmpath)) * sizeof(char));
   220        sprintf(message, format, jvmpath);
   221        ReportErrorMessage(message, JNI_TRUE);
   222        exit(4);
   223     }
   224   }
   226 #endif  /* ifndef GAMMA */
   228 }
   231 static jboolean
   232 LoadMSVCRT()
   233 {
   234     // Only do this once
   235     static int loaded = 0;
   236     char crtpath[MAXPATHLEN];
   238     if (!loaded) {
   239         /*
   240          * The Microsoft C Runtime Library needs to be loaded first.  A copy is
   241          * assumed to be present in the "JRE path" directory.  If it is not found
   242          * there (or "JRE path" fails to resolve), skip the explicit load and let
   243          * nature take its course, which is likely to be a failure to execute.
   244          */
   245         if (GetJREPath(crtpath, MAXPATHLEN)) {
   246             (void)strcat(crtpath, "\\bin\\" CRT_DLL);   /* Add crt dll */
   247             if (_launcher_debug) {
   248                 printf("CRT path is %s\n", crtpath);
   249             }
   250             if (_access(crtpath, 0) == 0) {
   251                 if (LoadLibrary(crtpath) == 0) {
   252                     ReportErrorMessage2("Error loading: %s", crtpath, JNI_TRUE);
   253                     return JNI_FALSE;
   254                 }
   255             }
   256         }
   257         loaded = 1;
   258     }
   259     return JNI_TRUE;
   260 }
   262 /*
   263  * The preJVMStart is a function in the jkernel.dll, which
   264  * performs the final step of synthesizing back the decomposed
   265  * modules  (partial install) to the full JRE. Any tool which
   266  * uses the  JRE must peform this step to ensure the complete synthesis.
   267  * The EnsureJreInstallation function calls preJVMStart based on
   268  * the conditions outlined below, noting that the operation
   269  * will fail silently if any of conditions are not met.
   270  * NOTE: this call must be made before jvm.dll is loaded, or jvm.cfg
   271  * is read, since jvm.cfg will be modified by the preJVMStart.
   272  * 1. Are we on a supported platform.
   273  * 2. Find the location of the JRE or the Kernel JRE.
   274  * 3. check existence of JREHOME/lib/bundles
   275  * 4. check jkernel.dll and invoke the entry-point
   276  */
   277 typedef VOID (WINAPI *PREJVMSTART)();
   279 static void
   280 EnsureJreInstallation(const char* jrepath)
   281 {
   282     HINSTANCE handle;
   283     char tmpbuf[MAXPATHLEN];
   284     PREJVMSTART PreJVMStart;
   285     struct stat s;
   287     /* 32 bit windows only please */
   288     if (strcmp(GetArch(), "i386") != 0 ) {
   289         if (_launcher_debug) {
   290             printf("EnsureJreInstallation:unsupported platform\n");
   291         }
   292         return;
   293     }
   294     /* Does our bundle directory exist ? */
   295     strcpy(tmpbuf, jrepath);
   296     strcat(tmpbuf, "\\lib\\bundles");
   297     if (stat(tmpbuf, &s) != 0) {
   298         if (_launcher_debug) {
   299             printf("EnsureJreInstallation:<%s>:not found\n", tmpbuf);
   300         }
   301         return;
   302     }
   303     /* Does our jkernel dll exist ? */
   304     strcpy(tmpbuf, jrepath);
   305     strcat(tmpbuf, "\\bin\\jkernel.dll");
   306     if (stat(tmpbuf, &s) != 0) {
   307         if (_launcher_debug) {
   308             printf("EnsureJreInstallation:<%s>:not found\n", tmpbuf);
   309         }
   310         return;
   311     }
   312     /* The Microsoft C Runtime Library needs to be loaded first. */
   313     if (!LoadMSVCRT()) {
   314         if (_launcher_debug) {
   315             printf("EnsureJreInstallation:could not load C runtime DLL\n");
   316         }
   317         return;
   318     }
   319     /* Load the jkernel.dll */
   320     if ((handle = LoadLibrary(tmpbuf)) == 0) {
   321         if (_launcher_debug) {
   322             printf("EnsureJreInstallation:%s:load failed\n", tmpbuf);
   323         }
   324         return;
   325     }
   326     /* Get the function address */
   327     PreJVMStart = (PREJVMSTART)GetProcAddress(handle, "preJVMStart");
   328     if (PreJVMStart == NULL) {
   329         if (_launcher_debug) {
   330             printf("EnsureJreInstallation:preJVMStart:function lookup failed\n");
   331         }
   332         FreeLibrary(handle);
   333         return;
   334     }
   335     PreJVMStart();
   336     if (_launcher_debug) {
   337         printf("EnsureJreInstallation:preJVMStart:called\n");
   338     }
   339     FreeLibrary(handle);
   340     return;
   341 }
   343 /*
   344  * Find path to JRE based on .exe's location or registry settings.
   345  */
   346 jboolean
   347 GetJREPath(char *path, jint pathsize)
   348 {
   349     char javadll[MAXPATHLEN];
   350     struct stat s;
   352     if (GetApplicationHome(path, pathsize)) {
   353         /* Is JRE co-located with the application? */
   354         sprintf(javadll, "%s\\bin\\" JAVA_DLL, path);
   355         if (stat(javadll, &s) == 0) {
   356             goto found;
   357         }
   359         /* Does this app ship a private JRE in <apphome>\jre directory? */
   360         sprintf(javadll, "%s\\jre\\bin\\" JAVA_DLL, path);
   361         if (stat(javadll, &s) == 0) {
   362             strcat(path, "\\jre");
   363             goto found;
   364         }
   365     }
   367 #ifndef GAMMA
   368     /* Look for a public JRE on this machine. */
   369     if (GetPublicJREHome(path, pathsize)) {
   370         goto found;
   371     }
   372 #endif
   374     fprintf(stderr, "Error: could not find " JAVA_DLL "\n");
   375     return JNI_FALSE;
   377  found:
   378     if (_launcher_debug)
   379       printf("JRE path is %s\n", path);
   380     return JNI_TRUE;
   381 }
   383 /*
   384  * Given a JRE location and a JVM type, construct what the name the
   385  * JVM shared library will be.  Return true, if such a library
   386  * exists, false otherwise.
   387  */
   388 static jboolean
   389 GetJVMPath(const char *jrepath, const char *jvmtype,
   390            char *jvmpath, jint jvmpathsize)
   391 {
   392     struct stat s;
   394 #ifndef GAMMA
   395     if (strchr(jvmtype, '/') || strchr(jvmtype, '\\')) {
   396         sprintf(jvmpath, "%s\\" JVM_DLL, jvmtype);
   397     } else {
   398         sprintf(jvmpath, "%s\\bin\\%s\\" JVM_DLL, jrepath, jvmtype);
   399     }
   400 #else
   401     /*
   402      * For gamma launcher, JVM is either built-in or in the same directory.
   403      * Either way we return "<exe_path>/jvm.dll" where <exe_path> is the
   404      * directory where gamma launcher is located.
   405      */
   407     char *p;
   408     GetModuleFileName(0, jvmpath, jvmpathsize);
   410     p = strrchr(jvmpath, '\\');
   411     if (p) {
   412        /* replace executable name with libjvm.so */
   413        snprintf(p + 1, jvmpathsize - (p + 1 - jvmpath), "%s", JVM_DLL);
   414     } else {
   415        /* this case shouldn't happen */
   416        snprintf(jvmpath, jvmpathsize, "%s", JVM_DLL);
   417     }
   418 #endif /* ifndef GAMMA */
   420     if (stat(jvmpath, &s) == 0) {
   421         return JNI_TRUE;
   422     } else {
   423         return JNI_FALSE;
   424     }
   425 }
   427 /*
   428  * Load a jvm from "jvmpath" and initialize the invocation functions.
   429  */
   430 jboolean
   431 LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)
   432 {
   433 #ifdef GAMMA
   434     /* JVM is directly linked with gamma launcher; no Loadlibrary() */
   435     ifn->CreateJavaVM = JNI_CreateJavaVM;
   436     ifn->GetDefaultJavaVMInitArgs = JNI_GetDefaultJavaVMInitArgs;
   437     return JNI_TRUE;
   438 #else
   439     HINSTANCE handle;
   441     if (_launcher_debug) {
   442         printf("JVM path is %s\n", jvmpath);
   443     }
   445     /* The Microsoft C Runtime Library needs to be loaded first. */
   446     LoadMSVCRT();
   448     /* Load the Java VM DLL */
   449     if ((handle = LoadLibrary(jvmpath)) == 0) {
   450         ReportErrorMessage2("Error loading: %s", (char *)jvmpath, JNI_TRUE);
   451         return JNI_FALSE;
   452     }
   454     /* Now get the function addresses */
   455     ifn->CreateJavaVM =
   456         (void *)GetProcAddress(handle, "JNI_CreateJavaVM");
   457     ifn->GetDefaultJavaVMInitArgs =
   458         (void *)GetProcAddress(handle, "JNI_GetDefaultJavaVMInitArgs");
   459     if (ifn->CreateJavaVM == 0 || ifn->GetDefaultJavaVMInitArgs == 0) {
   460         ReportErrorMessage2("Error: can't find JNI interfaces in: %s",
   461                             (char *)jvmpath, JNI_TRUE);
   462         return JNI_FALSE;
   463     }
   465     return JNI_TRUE;
   466 #endif /* ifndef GAMMA */
   467 }
   469 /*
   470  * If app is "c:\foo\bin\javac", then put "c:\foo" into buf.
   471  */
   472 jboolean
   473 GetApplicationHome(char *buf, jint bufsize)
   474 {
   475 #ifndef GAMMA
   476     char *cp;
   477     GetModuleFileName(0, buf, bufsize);
   478     *strrchr(buf, '\\') = '\0'; /* remove .exe file name */
   479     if ((cp = strrchr(buf, '\\')) == 0) {
   480         /* This happens if the application is in a drive root, and
   481          * there is no bin directory. */
   482         buf[0] = '\0';
   483         return JNI_FALSE;
   484     }
   485     *cp = '\0';  /* remove the bin\ part */
   486     return JNI_TRUE;
   488 #else /* ifndef GAMMA */
   490     char env[MAXPATHLEN + 1];
   492     /* gamma launcher uses ALT_JAVA_HOME environment variable or jdkpath.txt file to find JDK/JRE */
   494     if (getenv("ALT_JAVA_HOME") != NULL) {
   495        snprintf(buf, bufsize, "%s", getenv("ALT_JAVA_HOME"));
   496     }
   497     else {
   498        char path[MAXPATHLEN + 1];
   499        char* p;
   500        int len;
   501        FILE* fp;
   503        // find the path to the currect executable
   504        len = GetModuleFileName(NULL, path, MAXPATHLEN + 1);
   505        if (len == 0 || len > MAXPATHLEN) {
   506           printf("Could not get directory of current executable.");
   507           return JNI_FALSE;
   508        }
   509        // remove last path component ("hotspot.exe")
   510        p = strrchr(path, '\\');
   511        if (p == NULL) {
   512           printf("Could not parse directory of current executable.\n");
   513           return JNI_FALSE;
   514        }
   515        *p = '\0';
   517        // open jdkpath.txt and read JAVA_HOME from it
   518        if (strlen(path) + strlen("\\jdkpath.txt") + 1 >= MAXPATHLEN) {
   519           printf("Path too long: %s\n", path);
   520           return JNI_FALSE;
   521        }
   522        strcat(path, "\\jdkpath.txt");
   523        fp = fopen(path, "r");
   524        if (fp == NULL) {
   525           printf("Could not open file %s to get path to JDK.\n", path);
   526           return JNI_FALSE;
   527        }
   529        if (fgets(buf, bufsize, fp) == NULL) {
   530           printf("Could not read from file %s to get path to JDK.\n", path);
   531           fclose(fp);
   532           return JNI_FALSE;
   533        }
   534        // trim the buffer
   535        p = buf + strlen(buf) - 1;
   536        while(isspace(*p)) {
   537           *p = '\0';
   538           p--;
   539        }
   540        fclose(fp);
   541     }
   543     _snprintf(env, MAXPATHLEN, "JAVA_HOME=%s", buf);
   544     _putenv(env);
   546     return JNI_TRUE;
   547 #endif /* ifndef GAMMA */
   548 }
   550 #ifdef JAVAW
   551 __declspec(dllimport) char **__initenv;
   553 int WINAPI
   554 WinMain(HINSTANCE inst, HINSTANCE previnst, LPSTR cmdline, int cmdshow)
   555 {
   556     int   ret;
   558     __initenv = _environ;
   559     ret = main(__argc, __argv);
   561     return ret;
   562 }
   563 #endif
   565 #ifndef GAMMA
   567 /*
   568  * Helpers to look in the registry for a public JRE.
   569  */
   570                     /* Same for 1.5.0, 1.5.1, 1.5.2 etc. */
   571 #define DOTRELEASE  JDK_MAJOR_VERSION "." JDK_MINOR_VERSION
   572 #define JRE_KEY     "Software\\JavaSoft\\Java Runtime Environment"
   574 static jboolean
   575 GetStringFromRegistry(HKEY key, const char *name, char *buf, jint bufsize)
   576 {
   577     DWORD type, size;
   579     if (RegQueryValueEx(key, name, 0, &type, 0, &size) == 0
   580         && type == REG_SZ
   581         && (size < (unsigned int)bufsize)) {
   582         if (RegQueryValueEx(key, name, 0, 0, buf, &size) == 0) {
   583             return JNI_TRUE;
   584         }
   585     }
   586     return JNI_FALSE;
   587 }
   589 static jboolean
   590 GetPublicJREHome(char *buf, jint bufsize)
   591 {
   592     HKEY key, subkey;
   593     char version[MAXPATHLEN];
   595     /*
   596      * Note: There is a very similar implementation of the following
   597      * registry reading code in the Windows java control panel (javacp.cpl).
   598      * If there are bugs here, a similar bug probably exists there.  Hence,
   599      * changes here require inspection there.
   600      */
   602     /* Find the current version of the JRE */
   603     if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, JRE_KEY, 0, KEY_READ, &key) != 0) {
   604         fprintf(stderr, "Error opening registry key '" JRE_KEY "'\n");
   605         return JNI_FALSE;
   606     }
   608     if (!GetStringFromRegistry(key, "CurrentVersion",
   609                                version, sizeof(version))) {
   610         fprintf(stderr, "Failed reading value of registry key:\n\t"
   611                 JRE_KEY "\\CurrentVersion\n");
   612         RegCloseKey(key);
   613         return JNI_FALSE;
   614     }
   616     if (strcmp(version, DOTRELEASE) != 0) {
   617         fprintf(stderr, "Registry key '" JRE_KEY "\\CurrentVersion'\nhas "
   618                 "value '%s', but '" DOTRELEASE "' is required.\n", version);
   619         RegCloseKey(key);
   620         return JNI_FALSE;
   621     }
   623     /* Find directory where the current version is installed. */
   624     if (RegOpenKeyEx(key, version, 0, KEY_READ, &subkey) != 0) {
   625         fprintf(stderr, "Error opening registry key '"
   626                 JRE_KEY "\\%s'\n", version);
   627         RegCloseKey(key);
   628         return JNI_FALSE;
   629     }
   631     if (!GetStringFromRegistry(subkey, "JavaHome", buf, bufsize)) {
   632         fprintf(stderr, "Failed reading value of registry key:\n\t"
   633                 JRE_KEY "\\%s\\JavaHome\n", version);
   634         RegCloseKey(key);
   635         RegCloseKey(subkey);
   636         return JNI_FALSE;
   637     }
   639     if (_launcher_debug) {
   640         char micro[MAXPATHLEN];
   641         if (!GetStringFromRegistry(subkey, "MicroVersion", micro,
   642                                    sizeof(micro))) {
   643             printf("Warning: Can't read MicroVersion\n");
   644             micro[0] = '\0';
   645         }
   646         printf("Version major.minor.micro = %s.%s\n", version, micro);
   647     }
   649     RegCloseKey(key);
   650     RegCloseKey(subkey);
   651     return JNI_TRUE;
   652 }
   654 #endif /* ifndef GAMMA */
   656 /*
   657  * Support for doing cheap, accurate interval timing.
   658  */
   659 static jboolean counterAvailable = JNI_FALSE;
   660 static jboolean counterInitialized = JNI_FALSE;
   661 static LARGE_INTEGER counterFrequency;
   663 jlong CounterGet()
   664 {
   665     LARGE_INTEGER count;
   667     if (!counterInitialized) {
   668         counterAvailable = QueryPerformanceFrequency(&counterFrequency);
   669         counterInitialized = JNI_TRUE;
   670     }
   671     if (!counterAvailable) {
   672         return 0;
   673     }
   674     QueryPerformanceCounter(&count);
   675     return (jlong)(count.QuadPart);
   676 }
   678 jlong Counter2Micros(jlong counts)
   679 {
   680     if (!counterAvailable || !counterInitialized) {
   681         return 0;
   682     }
   683     return (counts * 1000 * 1000)/counterFrequency.QuadPart;
   684 }
   686 void ReportErrorMessage(char * message, jboolean always) {
   687 #ifdef JAVAW
   688   if (message != NULL) {
   689     MessageBox(NULL, message, "Java Virtual Machine Launcher",
   690                (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
   691   }
   692 #else
   693   if (always) {
   694     fprintf(stderr, "%s\n", message);
   695   }
   696 #endif
   697 }
   699 void ReportErrorMessage2(char * format, char * string, jboolean always) {
   700   /*
   701    * The format argument must be a printf format string with one %s
   702    * argument, which is passed the string argument.
   703    */
   704 #ifdef JAVAW
   705   size_t size;
   706   char * message;
   707   size = strlen(format) + strlen(string);
   708   message = (char*)JLI_MemAlloc(size*sizeof(char));
   709   sprintf(message, (const char *)format, string);
   711   if (message != NULL) {
   712     MessageBox(NULL, message, "Java Virtual Machine Launcher",
   713                (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
   714     JLI_MemFree(message);
   715   }
   716 #else
   717   if (always) {
   718     fprintf(stderr, (const char *)format, string);
   719     fprintf(stderr, "\n");
   720   }
   721 #endif
   722 }
   724 /*
   725  * As ReportErrorMessage2 (above) except the system message (if any)
   726  * associated with this error is written to a second %s format specifier
   727  * in the format argument.
   728  */
   729 void ReportSysErrorMessage2(char * format, char * string, jboolean always) {
   730   int   save_errno = errno;
   731   DWORD errval;
   732   int   freeit = 0;
   733   char  *errtext = NULL;
   735   if ((errval = GetLastError()) != 0) {         /* Platform SDK / DOS Error */
   736     int n = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|
   737       FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_ALLOCATE_BUFFER,
   738       NULL, errval, 0, (LPTSTR)&errtext, 0, NULL);
   739     if (errtext == NULL || n == 0) {            /* Paranoia check */
   740       errtext = "";
   741       n = 0;
   742     } else {
   743       freeit = 1;
   744       if (n > 2) {                              /* Drop final CR, LF */
   745         if (errtext[n - 1] == '\n') n--;
   746         if (errtext[n - 1] == '\r') n--;
   747         errtext[n] = '\0';
   748       }
   749     }
   750   } else        /* C runtime error that has no corresponding DOS error code */
   751     errtext = strerror(save_errno);
   753 #ifdef JAVAW
   754   {
   755     size_t size;
   756     char * message;
   757     size = strlen(format) + strlen(string) + strlen(errtext);
   758     message = (char*)JLI_MemAlloc(size*sizeof(char));
   759     sprintf(message, (const char *)format, string, errtext);
   761     if (message != NULL) {
   762       MessageBox(NULL, message, "Java Virtual Machine Launcher",
   763                (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
   764       JLI_MemFree(message);
   765     }
   766   }
   767 #else
   768   if (always) {
   769     fprintf(stderr, (const char *)format, string, errtext);
   770     fprintf(stderr, "\n");
   771   }
   772 #endif
   773   if (freeit)
   774     (void)LocalFree((HLOCAL)errtext);
   775 }
   777 void  ReportExceptionDescription(JNIEnv * env) {
   778 #ifdef JAVAW
   779   /*
   780    * This code should be replaced by code which opens a window with
   781    * the exception detail message.
   782    */
   783   (*env)->ExceptionDescribe(env);
   784 #else
   785   (*env)->ExceptionDescribe(env);
   786 #endif
   787 }
   790 /*
   791  * Return JNI_TRUE for an option string that has no effect but should
   792  * _not_ be passed on to the vm; return JNI_FALSE otherwise. On
   793  * windows, there are no options that should be screened in this
   794  * manner.
   795  */
   796 jboolean RemovableMachineDependentOption(char * option) {
   797 #ifdef ENABLE_AWT_PRELOAD
   798     if (awtPreloadD3D < 0) {
   799         /* Tests the command line parameter only if not set yet. */
   800         if (GetBoolParamValue(PARAM_PRELOAD_D3D, option) == 1) {
   801             awtPreloadD3D = 1;
   802         }
   803     }
   804     if (awtPreloadD3D != 0) {
   805         /* Don't test the command line parameters if already disabled. */
   806         if (GetBoolParamValue(PARAM_NODDRAW, option) == 1
   807             || GetBoolParamValue(PARAM_D3D, option) == 0
   808             || GetBoolParamValue(PARAM_OPENGL, option) == 1)
   809         {
   810             awtPreloadD3D = 0;
   811         }
   812     }
   813 #endif /* ENABLE_AWT_PRELOAD */
   815     return JNI_FALSE;
   816 }
   818 void PrintMachineDependentOptions() {
   819   return;
   820 }
   822 #ifndef GAMMA
   824 jboolean
   825 ServerClassMachine() {
   826   jboolean result = JNI_FALSE;
   827 #if   defined(NEVER_ACT_AS_SERVER_CLASS_MACHINE)
   828   result = JNI_FALSE;
   829 #elif defined(ALWAYS_ACT_AS_SERVER_CLASS_MACHINE)
   830   result = JNI_TRUE;
   831 #endif
   832   return result;
   833 }
   835 /*
   836  * Determine if there is an acceptable JRE in the registry directory top_key.
   837  * Upon locating the "best" one, return a fully qualified path to it.
   838  * "Best" is defined as the most advanced JRE meeting the constraints
   839  * contained in the manifest_info. If no JRE in this directory meets the
   840  * constraints, return NULL.
   841  *
   842  * It doesn't matter if we get an error reading the registry, or we just
   843  * don't find anything interesting in the directory.  We just return NULL
   844  * in either case.
   845  */
   846 static char *
   847 ProcessDir(manifest_info* info, HKEY top_key) {
   848     DWORD   index = 0;
   849     HKEY    ver_key;
   850     char    name[MAXNAMELEN];
   851     int     len;
   852     char    *best = NULL;
   854     /*
   855      * Enumerate "<top_key>/SOFTWARE/JavaSoft/Java Runtime Environment"
   856      * searching for the best available version.
   857      */
   858     while (RegEnumKey(top_key, index, name, MAXNAMELEN) == ERROR_SUCCESS) {
   859         index++;
   860         if (JLI_AcceptableRelease(name, info->jre_version))
   861             if ((best == NULL) || (JLI_ExactVersionId(name, best) > 0)) {
   862                 if (best != NULL)
   863                     JLI_MemFree(best);
   864                 best = JLI_StringDup(name);
   865             }
   866     }
   868     /*
   869      * Extract "JavaHome" from the "best" registry directory and return
   870      * that path.  If no appropriate version was located, or there is an
   871      * error in extracting the "JavaHome" string, return null.
   872      */
   873     if (best == NULL)
   874         return (NULL);
   875     else {
   876         if (RegOpenKeyEx(top_key, best, 0, KEY_READ, &ver_key)
   877           != ERROR_SUCCESS) {
   878             JLI_MemFree(best);
   879             if (ver_key != NULL)
   880                 RegCloseKey(ver_key);
   881             return (NULL);
   882         }
   883         JLI_MemFree(best);
   884         len = MAXNAMELEN;
   885         if (RegQueryValueEx(ver_key, "JavaHome", NULL, NULL, (LPBYTE)name, &len)
   886           != ERROR_SUCCESS) {
   887             if (ver_key != NULL)
   888                 RegCloseKey(ver_key);
   889             return (NULL);
   890         }
   891         if (ver_key != NULL)
   892             RegCloseKey(ver_key);
   893         return (JLI_StringDup(name));
   894     }
   895 }
   897 /*
   898  * This is the global entry point. It examines the host for the optimal
   899  * JRE to be used by scanning a set of registry entries.  This set of entries
   900  * is hardwired on Windows as "Software\JavaSoft\Java Runtime Environment"
   901  * under the set of roots "{ HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }".
   902  *
   903  * This routine simply opens each of these registry directories before passing
   904  * control onto ProcessDir().
   905  */
   906 char *
   907 LocateJRE(manifest_info* info) {
   908     HKEY    key = NULL;
   909     char    *path;
   910     int     key_index;
   911     HKEY    root_keys[2] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE };
   913     for (key_index = 0; key_index <= 1; key_index++) {
   914         if (RegOpenKeyEx(root_keys[key_index], JRE_KEY, 0, KEY_READ, &key)
   915           == ERROR_SUCCESS)
   916             if ((path = ProcessDir(info, key)) != NULL) {
   917                 if (key != NULL)
   918                     RegCloseKey(key);
   919                 return (path);
   920             }
   921         if (key != NULL)
   922             RegCloseKey(key);
   923     }
   924     return NULL;
   925 }
   928 /*
   929  * Local helper routine to isolate a single token (option or argument)
   930  * from the command line.
   931  *
   932  * This routine accepts a pointer to a character pointer.  The first
   933  * token (as defined by MSDN command-line argument syntax) is isolated
   934  * from that string.
   935  *
   936  * Upon return, the input character pointer pointed to by the parameter s
   937  * is updated to point to the remainding, unscanned, portion of the string,
   938  * or to a null character if the entire string has been consummed.
   939  *
   940  * This function returns a pointer to a null-terminated string which
   941  * contains the isolated first token, or to the null character if no
   942  * token could be isolated.
   943  *
   944  * Note the side effect of modifying the input string s by the insertion
   945  * of a null character, making it two strings.
   946  *
   947  * See "Parsing C Command-Line Arguments" in the MSDN Library for the
   948  * parsing rule details.  The rule summary from that specification is:
   949  *
   950  *  * Arguments are delimited by white space, which is either a space or a tab.
   951  *
   952  *  * A string surrounded by double quotation marks is interpreted as a single
   953  *    argument, regardless of white space contained within. A quoted string can
   954  *    be embedded in an argument. Note that the caret (^) is not recognized as
   955  *    an escape character or delimiter.
   956  *
   957  *  * A double quotation mark preceded by a backslash, \", is interpreted as a
   958  *    literal double quotation mark (").
   959  *
   960  *  * Backslashes are interpreted literally, unless they immediately precede a
   961  *    double quotation mark.
   962  *
   963  *  * If an even number of backslashes is followed by a double quotation mark,
   964  *    then one backslash (\) is placed in the argv array for every pair of
   965  *    backslashes (\\), and the double quotation mark (") is interpreted as a
   966  *    string delimiter.
   967  *
   968  *  * If an odd number of backslashes is followed by a double quotation mark,
   969  *    then one backslash (\) is placed in the argv array for every pair of
   970  *    backslashes (\\) and the double quotation mark is interpreted as an
   971  *    escape sequence by the remaining backslash, causing a literal double
   972  *    quotation mark (") to be placed in argv.
   973  */
   974 static char*
   975 nextarg(char** s) {
   976     char    *p = *s;
   977     char    *head;
   978     int     slashes = 0;
   979     int     inquote = 0;
   981     /*
   982      * Strip leading whitespace, which MSDN defines as only space or tab.
   983      * (Hence, no locale specific "isspace" here.)
   984      */
   985     while (*p != (char)0 && (*p == ' ' || *p == '\t'))
   986         p++;
   987     head = p;                   /* Save the start of the token to return */
   989     /*
   990      * Isolate a token from the command line.
   991      */
   992     while (*p != (char)0 && (inquote || !(*p == ' ' || *p == '\t'))) {
   993         if (*p == '\\' && *(p+1) == '"' && slashes % 2 == 0)
   994             p++;
   995         else if (*p == '"')
   996             inquote = !inquote;
   997         slashes = (*p++ == '\\') ? slashes + 1 : 0;
   998     }
  1000     /*
  1001      * If the token isolated isn't already terminated in a "char zero",
  1002      * then replace the whitespace character with one and move to the
  1003      * next character.
  1004      */
  1005     if (*p != (char)0)
  1006         *p++ = (char)0;
  1008     /*
  1009      * Update the parameter to point to the head of the remaining string
  1010      * reflecting the command line and return a pointer to the leading
  1011      * token which was isolated from the command line.
  1012      */
  1013     *s = p;
  1014     return (head);
  1017 /*
  1018  * Local helper routine to return a string equivalent to the input string
  1019  * s, but with quotes removed so the result is a string as would be found
  1020  * in argv[].  The returned string should be freed by a call to JLI_MemFree().
  1022  * The rules for quoting (and escaped quotes) are:
  1024  *  1 A double quotation mark preceded by a backslash, \", is interpreted as a
  1025  *    literal double quotation mark (").
  1027  *  2 Backslashes are interpreted literally, unless they immediately precede a
  1028  *    double quotation mark.
  1030  *  3 If an even number of backslashes is followed by a double quotation mark,
  1031  *    then one backslash (\) is placed in the argv array for every pair of
  1032  *    backslashes (\\), and the double quotation mark (") is interpreted as a
  1033  *    string delimiter.
  1035  *  4 If an odd number of backslashes is followed by a double quotation mark,
  1036  *    then one backslash (\) is placed in the argv array for every pair of
  1037  *    backslashes (\\) and the double quotation mark is interpreted as an
  1038  *    escape sequence by the remaining backslash, causing a literal double
  1039  *    quotation mark (") to be placed in argv.
  1040  */
  1041 static char*
  1042 unquote(const char *s) {
  1043     const char *p = s;          /* Pointer to the tail of the original string */
  1044     char *un = (char*)JLI_MemAlloc(strlen(s) + 1);  /* Ptr to unquoted string */
  1045     char *pun = un;             /* Pointer to the tail of the unquoted string */
  1047     while (*p != '\0') {
  1048         if (*p == '"') {
  1049             p++;
  1050         } else if (*p == '\\') {
  1051             const char *q = p + strspn(p,"\\");
  1052             if (*q == '"')
  1053                 do {
  1054                     *pun++ = '\\';
  1055                     p += 2;
  1056                  } while (*p == '\\' && p < q);
  1057             else
  1058                 while (p < q)
  1059                     *pun++ = *p++;
  1060         } else {
  1061             *pun++ = *p++;
  1064     *pun = '\0';
  1065     return un;
  1068 /*
  1069  * Given a path to a jre to execute, this routine checks if this process
  1070  * is indeed that jre.  If not, it exec's that jre.
  1072  * We want to actually check the paths rather than just the version string
  1073  * built into the executable, so that given version specification will yield
  1074  * the exact same Java environment, regardless of the version of the arbitrary
  1075  * launcher we start with.
  1076  */
  1077 void
  1078 ExecJRE(char *jre, char **argv) {
  1079     int     len;
  1080     char    *progname;
  1081     char    path[MAXPATHLEN + 1];
  1083     /*
  1084      * Determine the executable we are building (or in the rare case, running).
  1085      */
  1086 #ifdef JAVA_ARGS  /* javac, jar and friends. */
  1087     progname = "java";
  1088 #else             /* java, oldjava, javaw and friends */
  1089 #ifdef PROGNAME
  1090     progname = PROGNAME;
  1091 #else
  1093         char *s;
  1094         progname = *argv;
  1095         if ((s = strrchr(progname, FILE_SEPARATOR)) != 0) {
  1096             progname = s + 1;
  1099 #endif /* PROGNAME */
  1100 #endif /* JAVA_ARGS */
  1102     /*
  1103      * Resolve the real path to the currently running launcher.
  1104      */
  1105     len = GetModuleFileName(NULL, path, MAXPATHLEN + 1);
  1106     if (len == 0 || len > MAXPATHLEN) {
  1107         ReportSysErrorMessage2(
  1108           "Unable to resolve path to current %s executable: %s",
  1109           progname, JNI_TRUE);
  1110         exit(1);
  1113     if (_launcher_debug) {
  1114         printf("ExecJRE: old: %s\n", path);
  1115         printf("ExecJRE: new: %s\n", jre);
  1118     /*
  1119      * If the path to the selected JRE directory is a match to the initial
  1120      * portion of the path to the currently executing JRE, we have a winner!
  1121      * If so, just return. (strnicmp() is the Windows equiv. of strncasecmp().)
  1122      */
  1123     if (strnicmp(jre, path, strlen(jre)) == 0)
  1124         return;                 /* I am the droid you were looking for */
  1126     /*
  1127      * If this isn't the selected version, exec the selected version.
  1128      */
  1129     (void)strcat(strcat(strcpy(path, jre), "\\bin\\"), progname);
  1130     (void)strcat(path, ".exe");
  1132     /*
  1133      * Although Windows has an execv() entrypoint, it doesn't actually
  1134      * overlay a process: it can only create a new process and terminate
  1135      * the old process.  Therefore, any processes waiting on the initial
  1136      * process wake up and they shouldn't.  Hence, a chain of pseudo-zombie
  1137      * processes must be retained to maintain the proper wait semantics.
  1138      * Fortunately the image size of the launcher isn't too large at this
  1139      * time.
  1141      * If it weren't for this semantic flaw, the code below would be ...
  1143      *     execv(path, argv);
  1144      *     ReportErrorMessage2("Exec of %s failed\n", path, JNI_TRUE);
  1145      *     exit(1);
  1147      * The incorrect exec semantics could be addressed by:
  1149      *     exit((int)spawnv(_P_WAIT, path, argv));
  1151      * Unfortunately, a bug in Windows spawn/exec impementation prevents
  1152      * this from completely working.  All the Windows POSIX process creation
  1153      * interfaces are implemented as wrappers around the native Windows
  1154      * function CreateProcess().  CreateProcess() takes a single string
  1155      * to specify command line options and arguments, so the POSIX routine
  1156      * wrappers build a single string from the argv[] array and in the
  1157      * process, any quoting information is lost.
  1159      * The solution to this to get the original command line, to process it
  1160      * to remove the new multiple JRE options (if any) as was done for argv
  1161      * in the common SelectVersion() routine and finally to pass it directly
  1162      * to the native CreateProcess() Windows process control interface.
  1163      */
  1165         char    *cmdline;
  1166         char    *p;
  1167         char    *np;
  1168         char    *ocl;
  1169         char    *ccl;
  1170         char    *unquoted;
  1171         DWORD   exitCode;
  1172         STARTUPINFO si;
  1173         PROCESS_INFORMATION pi;
  1175         /*
  1176          * The following code block gets and processes the original command
  1177          * line, replacing the argv[0] equivalent in the command line with
  1178          * the path to the new executable and removing the appropriate
  1179          * Multiple JRE support options. Note that similar logic exists
  1180          * in the platform independent SelectVersion routine, but is
  1181          * replicated here due to the syntax of CreateProcess().
  1183          * The magic "+ 4" characters added to the command line length are
  1184          * 2 possible quotes around the path (argv[0]), a space after the
  1185          * path and a terminating null character.
  1186          */
  1187         ocl = GetCommandLine();
  1188         np = ccl = JLI_StringDup(ocl);
  1189         p = nextarg(&np);               /* Discard argv[0] */
  1190         cmdline = (char *)JLI_MemAlloc(strlen(path) + strlen(np) + 4);
  1191         if (strchr(path, (int)' ') == NULL && strchr(path, (int)'\t') == NULL)
  1192             cmdline = strcpy(cmdline, path);
  1193         else
  1194             cmdline = strcat(strcat(strcpy(cmdline, "\""), path), "\"");
  1196         while (*np != (char)0) {                /* While more command-line */
  1197             p = nextarg(&np);
  1198             if (*p != (char)0) {                /* If a token was isolated */
  1199                 unquoted = unquote(p);
  1200                 if (*unquoted == '-') {         /* Looks like an option */
  1201                     if (strcmp(unquoted, "-classpath") == 0 ||
  1202                       strcmp(unquoted, "-cp") == 0) {   /* Unique cp syntax */
  1203                         cmdline = strcat(strcat(cmdline, " "), p);
  1204                         p = nextarg(&np);
  1205                         if (*p != (char)0)      /* If a token was isolated */
  1206                             cmdline = strcat(strcat(cmdline, " "), p);
  1207                     } else if (strncmp(unquoted, "-version:", 9) != 0 &&
  1208                       strcmp(unquoted, "-jre-restrict-search") != 0 &&
  1209                       strcmp(unquoted, "-no-jre-restrict-search") != 0) {
  1210                         cmdline = strcat(strcat(cmdline, " "), p);
  1212                 } else {                        /* End of options */
  1213                     cmdline = strcat(strcat(cmdline, " "), p);
  1214                     cmdline = strcat(strcat(cmdline, " "), np);
  1215                     JLI_MemFree((void *)unquoted);
  1216                     break;
  1218                 JLI_MemFree((void *)unquoted);
  1221         JLI_MemFree((void *)ccl);
  1223         if (_launcher_debug) {
  1224             np = ccl = JLI_StringDup(cmdline);
  1225             p = nextarg(&np);
  1226             printf("ReExec Command: %s (%s)\n", path, p);
  1227             printf("ReExec Args: %s\n", np);
  1228             JLI_MemFree((void *)ccl);
  1230         (void)fflush(stdout);
  1231         (void)fflush(stderr);
  1233         /*
  1234          * The following code is modeled after a model presented in the
  1235          * Microsoft Technical Article "Moving Unix Applications to
  1236          * Windows NT" (March 6, 1994) and "Creating Processes" on MSDN
  1237          * (Februrary 2005).  It approximates UNIX spawn semantics with
  1238          * the parent waiting for termination of the child.
  1239          */
  1240         memset(&si, 0, sizeof(si));
  1241         si.cb =sizeof(STARTUPINFO);
  1242         memset(&pi, 0, sizeof(pi));
  1244         if (!CreateProcess((LPCTSTR)path,       /* executable name */
  1245           (LPTSTR)cmdline,                      /* command line */
  1246           (LPSECURITY_ATTRIBUTES)NULL,          /* process security attr. */
  1247           (LPSECURITY_ATTRIBUTES)NULL,          /* thread security attr. */
  1248           (BOOL)TRUE,                           /* inherits system handles */
  1249           (DWORD)0,                             /* creation flags */
  1250           (LPVOID)NULL,                         /* environment block */
  1251           (LPCTSTR)NULL,                        /* current directory */
  1252           (LPSTARTUPINFO)&si,                   /* (in) startup information */
  1253           (LPPROCESS_INFORMATION)&pi)) {        /* (out) process information */
  1254             ReportSysErrorMessage2("CreateProcess(%s, ...) failed: %s",
  1255               path, JNI_TRUE);
  1256               exit(1);
  1259         if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_FAILED) {
  1260             if (GetExitCodeProcess(pi.hProcess, &exitCode) == FALSE)
  1261                 exitCode = 1;
  1262         } else {
  1263             ReportErrorMessage("WaitForSingleObject() failed.", JNI_TRUE);
  1264             exitCode = 1;
  1267         CloseHandle(pi.hThread);
  1268         CloseHandle(pi.hProcess);
  1270         exit(exitCode);
  1275 #endif /* ifndef GAMMA */
  1278 /*
  1279  * Wrapper for platform dependent unsetenv function.
  1280  */
  1281 int
  1282 UnsetEnv(char *name)
  1284     int ret;
  1285     char *buf = JLI_MemAlloc(strlen(name) + 2);
  1286     buf = strcat(strcpy(buf, name), "=");
  1287     ret = _putenv(buf);
  1288     JLI_MemFree(buf);
  1289     return (ret);
  1292 /* --- Splash Screen shared library support --- */
  1294 static const char* SPLASHSCREEN_SO = "\\bin\\splashscreen.dll";
  1296 static HMODULE hSplashLib = NULL;
  1298 void* SplashProcAddress(const char* name) {
  1299     char libraryPath[MAXPATHLEN]; /* some extra space for strcat'ing SPLASHSCREEN_SO */
  1301     if (!GetJREPath(libraryPath, MAXPATHLEN)) {
  1302         return NULL;
  1304     if (strlen(libraryPath)+strlen(SPLASHSCREEN_SO) >= MAXPATHLEN) {
  1305         return NULL;
  1307     strcat(libraryPath, SPLASHSCREEN_SO);
  1309     if (!hSplashLib) {
  1310         hSplashLib = LoadLibrary(libraryPath);
  1312     if (hSplashLib) {
  1313         return GetProcAddress(hSplashLib, name);
  1314     } else {
  1315         return NULL;
  1319 void SplashFreeLibrary() {
  1320     if (hSplashLib) {
  1321         FreeLibrary(hSplashLib);
  1322         hSplashLib = NULL;
  1326 const char *
  1327 jlong_format_specifier() {
  1328     return "%I64d";
  1331 /*
  1332  * Block current thread and continue execution in a new thread
  1333  */
  1334 int
  1335 ContinueInNewThread(int (JNICALL *continuation)(void *), jlong stack_size, void * args) {
  1336     int rslt = 0;
  1337     unsigned thread_id;
  1339 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
  1340 #define STACK_SIZE_PARAM_IS_A_RESERVATION  (0x10000)
  1341 #endif
  1343     /*
  1344      * STACK_SIZE_PARAM_IS_A_RESERVATION is what we want, but it's not
  1345      * supported on older version of Windows. Try first with the flag; and
  1346      * if that fails try again without the flag. See MSDN document or HotSpot
  1347      * source (os_win32.cpp) for details.
  1348      */
  1349     HANDLE thread_handle =
  1350       (HANDLE)_beginthreadex(NULL,
  1351                              (unsigned)stack_size,
  1352                              continuation,
  1353                              args,
  1354                              STACK_SIZE_PARAM_IS_A_RESERVATION,
  1355                              &thread_id);
  1356     if (thread_handle == NULL) {
  1357       thread_handle =
  1358       (HANDLE)_beginthreadex(NULL,
  1359                              (unsigned)stack_size,
  1360                              continuation,
  1361                              args,
  1362                              0,
  1363                              &thread_id);
  1366     /* AWT preloading (AFTER main thread start) */
  1367 #ifdef ENABLE_AWT_PRELOAD
  1368     /* D3D preloading */
  1369     if (awtPreloadD3D != 0) {
  1370         char *envValue;
  1371         /* D3D routines checks env.var J2D_D3D if no appropriate
  1372          * command line params was specified
  1373          */
  1374         envValue = getenv("J2D_D3D");
  1375         if (envValue != NULL && stricmp(envValue, "false") == 0) {
  1376             awtPreloadD3D = 0;
  1378         /* Test that AWT preloading isn't disabled by J2D_D3D_PRELOAD env.var */
  1379         envValue = getenv("J2D_D3D_PRELOAD");
  1380         if (envValue != NULL && stricmp(envValue, "false") == 0) {
  1381             awtPreloadD3D = 0;
  1383         if (awtPreloadD3D < 0) {
  1384             /* If awtPreloadD3D is still undefined (-1), test
  1385              * if it is turned on by J2D_D3D_PRELOAD env.var.
  1386              * By default it's turned OFF.
  1387              */
  1388             awtPreloadD3D = 0;
  1389             if (envValue != NULL && stricmp(envValue, "true") == 0) {
  1390                 awtPreloadD3D = 1;
  1394     if (awtPreloadD3D) {
  1395         AWTPreload(D3D_PRELOAD_FUNC);
  1397 #endif /* ENABLE_AWT_PRELOAD */
  1399     if (thread_handle) {
  1400       WaitForSingleObject(thread_handle, INFINITE);
  1401       GetExitCodeThread(thread_handle, &rslt);
  1402       CloseHandle(thread_handle);
  1403     } else {
  1404       rslt = continuation(args);
  1407 #ifdef ENABLE_AWT_PRELOAD
  1408     if (awtPreloaded) {
  1409         AWTPreloadStop();
  1411 #endif /* ENABLE_AWT_PRELOAD */
  1413     return rslt;
  1416 /* Linux only, empty on windows. */
  1417 void SetJavaLauncherPlatformProps() {}
  1420 //==============================
  1421 // AWT preloading
  1422 #ifdef ENABLE_AWT_PRELOAD
  1424 typedef int FnPreloadStart(void);
  1425 typedef void FnPreloadStop(void);
  1426 static FnPreloadStop *fnPreloadStop = NULL;
  1427 static HMODULE hPreloadAwt = NULL;
  1429 /*
  1430  * Starts AWT preloading
  1431  */
  1432 int AWTPreload(const char *funcName)
  1434     int result = -1;
  1436     // load AWT library once (if several preload function should be called)
  1437     if (hPreloadAwt == NULL) {
  1438         // awt.dll is not loaded yet
  1439         char libraryPath[MAXPATHLEN];
  1440         int jrePathLen = 0;
  1441         HMODULE hJava = NULL;
  1442         HMODULE hVerify = NULL;
  1444         while (1) {
  1445             // awt.dll depends on jvm.dll & java.dll;
  1446             // jvm.dll is already loaded, so we need only java.dll;
  1447             // java.dll depends on MSVCRT lib & verify.dll.
  1448             if (!GetJREPath(libraryPath, MAXPATHLEN)) {
  1449                 break;
  1452             // save path length
  1453             jrePathLen = strlen(libraryPath);
  1455             // load msvcrt 1st
  1456             LoadMSVCRT();
  1458             // load verify.dll
  1459             strcat(libraryPath, "\\bin\\verify.dll");
  1460             hVerify = LoadLibrary(libraryPath);
  1461             if (hVerify == NULL) {
  1462                 break;
  1465             // restore jrePath
  1466             libraryPath[jrePathLen] = 0;
  1467             // load java.dll
  1468             strcat(libraryPath, "\\bin\\" JAVA_DLL);
  1469             hJava = LoadLibrary(libraryPath);
  1470             if (hJava == NULL) {
  1471                 break;
  1474             // restore jrePath
  1475             libraryPath[jrePathLen] = 0;
  1476             // load awt.dll
  1477             strcat(libraryPath, "\\bin\\awt.dll");
  1478             hPreloadAwt = LoadLibrary(libraryPath);
  1479             if (hPreloadAwt == NULL) {
  1480                 break;
  1483             // get "preloadStop" func ptr
  1484             fnPreloadStop = (FnPreloadStop *)GetProcAddress(hPreloadAwt, "preloadStop");
  1486             break;
  1490     if (hPreloadAwt != NULL) {
  1491         FnPreloadStart *fnInit = (FnPreloadStart *)GetProcAddress(hPreloadAwt, funcName);
  1492         if (fnInit != NULL) {
  1493             // don't forget to stop preloading
  1494             awtPreloaded = 1;
  1496             result = fnInit();
  1500     return result;
  1503 /*
  1504  * Terminates AWT preloading
  1505  */
  1506 void AWTPreloadStop() {
  1507     if (fnPreloadStop != NULL) {
  1508         fnPreloadStop();
  1512 #endif /* ENABLE_AWT_PRELOAD */

mercurial