1 /*
   2  * Copyright (c) 1997, 2017, 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 
  41 #define JVM_DLL "jvm.dll"
  42 #define JAVA_DLL "java.dll"
  43 
  44 /*
  45  * Prototypes.
  46  */
  47 static jboolean GetJVMPath(const char *jrepath, const char *jvmtype,
  48                            char *jvmpath, jint jvmpathsize);
  49 static jboolean GetJREPath(char *path, jint pathsize);
  50 
  51 #ifdef USE_REGISTRY_LOOKUP
  52 jboolean GetPublicJREHome(char *buf, jint bufsize);
  53 #endif
  54 
  55 /* We supports warmup for UI stack that is performed in parallel
  56  * to VM initialization.
  57  * This helps to improve startup of UI application as warmup phase
  58  * 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 needs
  61  * to be explicitly requested by passing -Dsun.awt.warmup=true property
  62  * (this is always the case for plugin/javaws).
  63  *
  64  * Implementation launches new thread after VM starts and use it to perform
  65  * warmup code (platform dependent).
  66  * This thread is later reused as AWT toolkit thread as graphics toolkit
  67  * 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 windows
  70  * and only if other flags do not prohibit this (e.g. OpenGL support requested).
  71  */
  72 #undef ENABLE_AWT_PRELOAD
  73 #ifndef JAVA_ARGS /* turn off AWT preloading for javac, jar, etc */
  74     /* CR6999872: fastdebug crashes if awt library is loaded before JVM is
  75      * initialized*/
  76     #if !defined(DEBUG)
  77         #define ENABLE_AWT_PRELOAD
  78     #endif
  79 #endif
  80 
  81 #ifdef ENABLE_AWT_PRELOAD
  82 /* "AWT was preloaded" flag;
  83  * turned on by AWTPreload().
  84  */
  85 int awtPreloaded = 0;
  86 
  87 /* Calls a function with the name specified
  88  * the function must be int(*fn)(void).
  89  */
  90 int AWTPreload(const char *funcName);
  91 /* stops AWT preloading */
  92 void AWTPreloadStop();
  93 
  94 /* D3D preloading */
  95 /* -1: not initialized; 0: OFF, 1: ON */
  96 int 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"
 105 
 106 /* Extracts value of a parameter with the specified name
 107  * 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  */
 112 const char * GetParamValue(const char *paramName, const char *arg) {
 113     size_t nameLen = JLI_StrLen(paramName);
 114     if (JLI_StrNCmp(paramName, arg, nameLen) == 0) {
 115         /* arg[nameLen] is valid (may contain final NULL) */
 116         if (arg[nameLen] == '=') {
 117             return arg + nameLen + 1;
 118         }
 119     }
 120     return NULL;
 121 }
 122 
 123 /* Checks if commandline argument contains property specified
 124  * 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  */
 129 int GetBoolParamValue(const char *paramName, const char *arg) {
 130     const char * paramValue = GetParamValue(paramName, arg);
 131     if (paramValue != NULL) {
 132         if (JLI_StrCaseCmp(paramValue, "true") == 0) {
 133             return 1;
 134         }
 135         if (JLI_StrCaseCmp(paramValue, "false") == 0) {
 136             return 0;
 137         }
 138     }
 139     return -1;
 140 }
 141 #endif /* ENABLE_AWT_PRELOAD */
 142 
 143 
 144 static jboolean _isjavaw = JNI_FALSE;
 145 
 146 
 147 jboolean
 148 IsJavaw()
 149 {
 150     return _isjavaw;
 151 }
 152 
 153 /*
 154  *
 155  */
 156 void
 157 CreateExecutionEnvironment(int *pargc, char ***pargv,
 158                            char *jrepath, jint so_jrepath,
 159                            char *jvmpath, jint so_jvmpath,
 160                            char *jvmcfg,  jint so_jvmcfg) {
 161 
 162     char *jvmtype;
 163     int i = 0;
 164     char** argv = *pargv;
 165 
 166     /* Find out where the JRE is that we will be using. */
 167     if (!GetJREPath(jrepath, so_jrepath)) {
 168         JLI_ReportErrorMessage(JRE_ERROR1);
 169         exit(2);
 170     }
 171 
 172     JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%sjvm.cfg",
 173         jrepath, FILESEP, FILESEP);
 174 
 175     /* Find the specified JVM type */
 176     if (ReadKnownVMs(jvmcfg, JNI_FALSE) < 1) {
 177         JLI_ReportErrorMessage(CFG_ERROR7);
 178         exit(1);
 179     }
 180 
 181     jvmtype = CheckJvmType(pargc, pargv, JNI_FALSE);
 182     if (JLI_StrCmp(jvmtype, "ERROR") == 0) {
 183         JLI_ReportErrorMessage(CFG_ERROR9);
 184         exit(4);
 185     }
 186 
 187     jvmpath[0] = '\0';
 188     if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath)) {
 189         JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath);
 190         exit(4);
 191     }
 192     /* If we got here, jvmpath has been correctly initialized. */
 193 
 194     /* Check if we need preload AWT */
 195 #ifdef ENABLE_AWT_PRELOAD
 196     argv = *pargv;
 197     for (i = 0; i < *pargc ; i++) {
 198         /* Tests the "turn on" parameter only if not set yet. */
 199         if (awtPreloadD3D < 0) {
 200             if (GetBoolParamValue(PARAM_PRELOAD_D3D, argv[i]) == 1) {
 201                 awtPreloadD3D = 1;
 202             }
 203         }
 204         /* Test parameters which can disable preloading if not already disabled. */
 205         if (awtPreloadD3D != 0) {
 206             if (GetBoolParamValue(PARAM_NODDRAW, argv[i]) == 1
 207                 || GetBoolParamValue(PARAM_D3D, argv[i]) == 0
 208                 || GetBoolParamValue(PARAM_OPENGL, argv[i]) == 1)
 209             {
 210                 awtPreloadD3D = 0;
 211                 /* no need to test the rest of the parameters */
 212                 break;
 213             }
 214         }
 215     }
 216 #endif /* ENABLE_AWT_PRELOAD */
 217 }
 218 
 219 
 220 static jboolean
 221 LoadMSVCRT()
 222 {
 223     // Only do this once
 224     static int loaded = 0;
 225     char crtpath[MAXPATHLEN];
 226 
 227     if (!loaded) {
 228         /*
 229          * The Microsoft C Runtime Library needs to be loaded first.  A copy is
 230          * assumed to be present in the "JRE path" directory.  If it is not found
 231          * there (or "JRE path" fails to resolve), skip the explicit load and let
 232          * 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 the
 234          * macro MSVCR_DLL_NAME.
 235          */
 236 #ifdef MSVCR_DLL_NAME
 237         if (GetJREPath(crtpath, MAXPATHLEN)) {
 238             if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") +
 239                     JLI_StrLen(MSVCR_DLL_NAME) >= MAXPATHLEN) {
 240                 JLI_ReportErrorMessage(JRE_ERROR11);
 241                 return JNI_FALSE;
 242             }
 243             (void)JLI_StrCat(crtpath, "\\bin\\" MSVCR_DLL_NAME);   /* Add crt dll */
 244             JLI_TraceLauncher("CRT path is %s\n", crtpath);
 245             if (_access(crtpath, 0) == 0) {
 246                 if (LoadLibrary(crtpath) == 0) {
 247                     JLI_ReportErrorMessage(DLL_ERROR4, crtpath);
 248                     return JNI_FALSE;
 249                 }
 250             }
 251         }
 252 #endif /* MSVCR_DLL_NAME */
 253 #ifdef MSVCP_DLL_NAME
 254         if (GetJREPath(crtpath, MAXPATHLEN)) {
 255             if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") +
 256                     JLI_StrLen(MSVCP_DLL_NAME) >= MAXPATHLEN) {
 257                 JLI_ReportErrorMessage(JRE_ERROR11);
 258                 return JNI_FALSE;
 259             }
 260             (void)JLI_StrCat(crtpath, "\\bin\\" MSVCP_DLL_NAME);   /* Add prt dll */
 261             JLI_TraceLauncher("PRT path is %s\n", crtpath);
 262             if (_access(crtpath, 0) == 0) {
 263                 if (LoadLibrary(crtpath) == 0) {
 264                     JLI_ReportErrorMessage(DLL_ERROR4, crtpath);
 265                     return JNI_FALSE;
 266                 }
 267             }
 268         }
 269 #endif /* MSVCP_DLL_NAME */
 270         loaded = 1;
 271     }
 272     return JNI_TRUE;
 273 }
 274 
 275 
 276 /*
 277  * Find path to JRE based on .exe's location or registry settings.
 278  */
 279 jboolean
 280 GetJREPath(char *path, jint pathsize)
 281 {
 282     char javadll[MAXPATHLEN];
 283     struct stat s;
 284 
 285     if (GetApplicationHome(path, pathsize)) {
 286         /* Is JRE co-located with the application? */
 287         JLI_Snprintf(javadll, sizeof(javadll), "%s\\bin\\" JAVA_DLL, path);
 288         if (stat(javadll, &s) == 0) {
 289             JLI_TraceLauncher("JRE path is %s\n", path);
 290             return JNI_TRUE;
 291         }
 292         /* ensure storage for path + \jre + NULL */
 293         if ((JLI_StrLen(path) + 4 + 1) > (size_t) pathsize) {
 294             JLI_TraceLauncher("Insufficient space to store JRE path\n");
 295             return JNI_FALSE;
 296         }
 297         /* Does this app ship a private JRE in <apphome>\jre directory? */
 298         JLI_Snprintf(javadll, sizeof (javadll), "%s\\jre\\bin\\" JAVA_DLL, path);
 299         if (stat(javadll, &s) == 0) {
 300             JLI_StrCat(path, "\\jre");
 301             JLI_TraceLauncher("JRE path is %s\n", path);
 302             return JNI_TRUE;
 303         }
 304     }
 305 
 306     /* Try getting path to JRE from path to JLI.DLL */
 307     if (GetApplicationHomeFromDll(path, pathsize)) {
 308         JLI_Snprintf(javadll, sizeof(javadll), "%s\\bin\\" JAVA_DLL, path);
 309         if (stat(javadll, &s) == 0) {
 310             JLI_TraceLauncher("JRE path is %s\n", path);
 311             return JNI_TRUE;
 312         }
 313     }
 314 
 315 #ifdef USE_REGISTRY_LOOKUP
 316     /* Lookup public JRE using Windows registry. */
 317     if (GetPublicJREHome(path, pathsize)) {
 318         JLI_TraceLauncher("JRE path is %s\n", path);
 319         return JNI_TRUE;
 320     }
 321 #endif
 322 
 323     JLI_ReportErrorMessage(JRE_ERROR8 JAVA_DLL);
 324     return JNI_FALSE;
 325 }
 326 
 327 /*
 328  * Given a JRE location and a JVM type, construct what the name the
 329  * JVM shared library will be.  Return true, if such a library
 330  * exists, false otherwise.
 331  */
 332 static jboolean
 333 GetJVMPath(const char *jrepath, const char *jvmtype,
 334            char *jvmpath, jint jvmpathsize)
 335 {
 336     struct stat s;
 337     if (JLI_StrChr(jvmtype, '/') || JLI_StrChr(jvmtype, '\\')) {
 338         JLI_Snprintf(jvmpath, jvmpathsize, "%s\\" JVM_DLL, jvmtype);
 339     } else {
 340         JLI_Snprintf(jvmpath, jvmpathsize, "%s\\bin\\%s\\" JVM_DLL,
 341                      jrepath, jvmtype);
 342     }
 343     if (stat(jvmpath, &s) == 0) {
 344         return JNI_TRUE;
 345     } else {
 346         return JNI_FALSE;
 347     }
 348 }
 349 
 350 /*
 351  * Load a jvm from "jvmpath" and initialize the invocation functions.
 352  */
 353 jboolean
 354 LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)
 355 {
 356     HINSTANCE handle;
 357 
 358     JLI_TraceLauncher("JVM path is %s\n", jvmpath);
 359 
 360     /*
 361      * The Microsoft C Runtime Library needs to be loaded first.  A copy is
 362      * assumed to be present in the "JRE path" directory.  If it is not found
 363      * there (or "JRE path" fails to resolve), skip the explicit load and let
 364      * nature take its course, which is likely to be a failure to execute.
 365      *
 366      */
 367     LoadMSVCRT();
 368 
 369     /* Load the Java VM DLL */
 370     if ((handle = LoadLibrary(jvmpath)) == 0) {
 371         JLI_ReportErrorMessage(DLL_ERROR4, (char *)jvmpath);
 372         return JNI_FALSE;
 373     }
 374 
 375     /* Now get the function addresses */
 376     ifn->CreateJavaVM =
 377         (void *)GetProcAddress(handle, "JNI_CreateJavaVM");
 378     ifn->GetDefaultJavaVMInitArgs =
 379         (void *)GetProcAddress(handle, "JNI_GetDefaultJavaVMInitArgs");
 380     if (ifn->CreateJavaVM == 0 || ifn->GetDefaultJavaVMInitArgs == 0) {
 381         JLI_ReportErrorMessage(JNI_ERROR1, (char *)jvmpath);
 382         return JNI_FALSE;
 383     }
 384 
 385     return JNI_TRUE;
 386 }
 387 
 388 /*
 389  * Removes the trailing file name and one sub-folder from a path.
 390  * If buf is "c:\foo\bin\javac", then put "c:\foo" into buf.
 391  */
 392 jboolean
 393 TruncatePath(char *buf)
 394 {
 395     char *cp;
 396     *JLI_StrRChr(buf, '\\') = '\0'; /* remove .exe file name */
 397     if ((cp = JLI_StrRChr(buf, '\\')) == 0) {
 398         /* This happens if the application is in a drive root, and
 399          * there is no bin directory. */
 400         buf[0] = '\0';
 401         return JNI_FALSE;
 402     }
 403     *cp = '\0'; /* remove the bin\ part */
 404     return JNI_TRUE;
 405 }
 406 
 407 /*
 408  * Retrieves the path to the JRE home by locating the executable file
 409  * of the current process and then truncating the path to the executable
 410  */
 411 jboolean
 412 GetApplicationHome(char *buf, jint bufsize)
 413 {
 414     GetModuleFileName(NULL, buf, bufsize);
 415     return TruncatePath(buf);
 416 }
 417 
 418 /*
 419  * Retrieves the path to the JRE home by locating JLI.DLL and
 420  * then truncating the path to JLI.DLL
 421  */
 422 jboolean
 423 GetApplicationHomeFromDll(char *buf, jint bufsize)
 424 {
 425     HMODULE module;
 426     DWORD flags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
 427                   GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT;
 428 
 429     if (GetModuleHandleEx(flags, (LPCSTR)&GetJREPath, &module) != 0) {
 430         if (GetModuleFileName(module, buf, bufsize) != 0) {
 431             return TruncatePath(buf);
 432         }
 433     }
 434     return JNI_FALSE;
 435 }
 436 
 437 /*
 438  * Support for doing cheap, accurate interval timing.
 439  */
 440 static jboolean counterAvailable = JNI_FALSE;
 441 static jboolean counterInitialized = JNI_FALSE;
 442 static LARGE_INTEGER counterFrequency;
 443 
 444 jlong CounterGet()
 445 {
 446     LARGE_INTEGER count;
 447 
 448     if (!counterInitialized) {
 449         counterAvailable = QueryPerformanceFrequency(&counterFrequency);
 450         counterInitialized = JNI_TRUE;
 451     }
 452     if (!counterAvailable) {
 453         return 0;
 454     }
 455     QueryPerformanceCounter(&count);
 456     return (jlong)(count.QuadPart);
 457 }
 458 
 459 jlong Counter2Micros(jlong counts)
 460 {
 461     if (!counterAvailable || !counterInitialized) {
 462         return 0;
 463     }
 464     return (counts * 1000 * 1000)/counterFrequency.QuadPart;
 465 }
 466 /*
 467  * windows snprintf does not guarantee a null terminator in the buffer,
 468  * if the computed size is equal to or greater than the buffer size,
 469  * as well as error conditions. This function guarantees a null terminator
 470  * under all these conditions. An unreasonable buffer or size will return
 471  * an error value. Under all other conditions this function will return the
 472  * size of the bytes actually written minus the null terminator, similar
 473  * to ansi snprintf api. Thus when calling this function the caller must
 474  * ensure storage for the null terminator.
 475  */
 476 int
 477 JLI_Snprintf(char* buffer, size_t size, const char* format, ...) {
 478     int rc;
 479     va_list vl;
 480     if (size == 0 || buffer == NULL)
 481         return -1;
 482     buffer[0] = '\0';
 483     va_start(vl, format);
 484     rc = vsnprintf(buffer, size, format, vl);
 485     va_end(vl);
 486     /* force a null terminator, if something is amiss */
 487     if (rc < 0) {
 488         /* apply ansi semantics */
 489         buffer[size - 1] = '\0';
 490         return (int)size;
 491     } else if (rc == size) {
 492         /* force a null terminator */
 493         buffer[size - 1] = '\0';
 494     }
 495     return rc;
 496 }
 497 
 498 void
 499 JLI_ReportErrorMessage(const char* fmt, ...) {
 500     va_list vl;
 501     va_start(vl,fmt);
 502 
 503     if (IsJavaw()) {
 504         char *message;
 505 
 506         /* get the length of the string we need */
 507         int n = _vscprintf(fmt, vl);
 508 
 509         message = (char *)JLI_MemAlloc(n + 1);
 510         _vsnprintf(message, n, fmt, vl);
 511         message[n]='\0';
 512         MessageBox(NULL, message, "Java Virtual Machine Launcher",
 513             (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
 514         JLI_MemFree(message);
 515     } else {
 516         vfprintf(stderr, fmt, vl);
 517         fprintf(stderr, "\n");
 518     }
 519     va_end(vl);
 520 }
 521 
 522 /*
 523  * Just like JLI_ReportErrorMessage, except that it concatenates the system
 524  * error message if any, its upto the calling routine to correctly
 525  * format the separation of the messages.
 526  */
 527 void
 528 JLI_ReportErrorMessageSys(const char *fmt, ...)
 529 {
 530     va_list vl;
 531 
 532     int save_errno = errno;
 533     DWORD       errval;
 534     jboolean freeit = JNI_FALSE;
 535     char  *errtext = NULL;
 536 
 537     va_start(vl, fmt);
 538 
 539     if ((errval = GetLastError()) != 0) {               /* Platform SDK / DOS Error */
 540         int n = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|
 541             FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_ALLOCATE_BUFFER,
 542             NULL, errval, 0, (LPTSTR)&errtext, 0, NULL);
 543         if (errtext == NULL || n == 0) {                /* Paranoia check */
 544             errtext = "";
 545             n = 0;
 546         } else {
 547             freeit = JNI_TRUE;
 548             if (n > 2) {                                /* Drop final CR, LF */
 549                 if (errtext[n - 1] == '\n') n--;
 550                 if (errtext[n - 1] == '\r') n--;
 551                 errtext[n] = '\0';
 552             }
 553         }
 554     } else {   /* C runtime error that has no corresponding DOS error code */
 555         errtext = strerror(save_errno);
 556     }
 557 
 558     if (IsJavaw()) {
 559         char *message;
 560         int mlen;
 561         /* get the length of the string we need */
 562         int len = mlen =  _vscprintf(fmt, vl) + 1;
 563         if (freeit) {
 564            mlen += (int)JLI_StrLen(errtext);
 565         }
 566 
 567         message = (char *)JLI_MemAlloc(mlen);
 568         _vsnprintf(message, len, fmt, vl);
 569         message[len]='\0';
 570 
 571         if (freeit) {
 572            JLI_StrCat(message, errtext);
 573         }
 574 
 575         MessageBox(NULL, message, "Java Virtual Machine Launcher",
 576             (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
 577 
 578         JLI_MemFree(message);
 579     } else {
 580         vfprintf(stderr, fmt, vl);
 581         if (freeit) {
 582            fprintf(stderr, "%s", errtext);
 583         }
 584     }
 585     if (freeit) {
 586         (void)LocalFree((HLOCAL)errtext);
 587     }
 588     va_end(vl);
 589 }
 590 
 591 void  JLI_ReportExceptionDescription(JNIEnv * env) {
 592     if (IsJavaw()) {
 593        /*
 594         * This code should be replaced by code which opens a window with
 595         * the exception detail message, for now atleast put a dialog up.
 596         */
 597         MessageBox(NULL, "A Java Exception has occurred.", "Java Virtual Machine Launcher",
 598                (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
 599     } else {
 600         (*env)->ExceptionDescribe(env);
 601     }
 602 }
 603 
 604 /*
 605  * Wrapper for platform dependent unsetenv function.
 606  */
 607 int
 608 UnsetEnv(char *name)
 609 {
 610     int ret;
 611     char *buf = JLI_MemAlloc(JLI_StrLen(name) + 2);
 612     buf = JLI_StrCat(JLI_StrCpy(buf, name), "=");
 613     ret = _putenv(buf);
 614     JLI_MemFree(buf);
 615     return (ret);
 616 }
 617 
 618 /* --- Splash Screen shared library support --- */
 619 
 620 static const char* SPLASHSCREEN_SO = "\\bin\\splashscreen.dll";
 621 
 622 static HMODULE hSplashLib = NULL;
 623 
 624 void* SplashProcAddress(const char* name) {
 625     char libraryPath[MAXPATHLEN]; /* some extra space for JLI_StrCat'ing SPLASHSCREEN_SO */
 626 
 627     if (!GetJREPath(libraryPath, MAXPATHLEN)) {
 628         return NULL;
 629     }
 630     if (JLI_StrLen(libraryPath)+JLI_StrLen(SPLASHSCREEN_SO) >= MAXPATHLEN) {
 631         return NULL;
 632     }
 633     JLI_StrCat(libraryPath, SPLASHSCREEN_SO);
 634 
 635     if (!hSplashLib) {
 636         hSplashLib = LoadLibrary(libraryPath);
 637     }
 638     if (hSplashLib) {
 639         return GetProcAddress(hSplashLib, name);
 640     } else {
 641         return NULL;
 642     }
 643 }
 644 
 645 void SplashFreeLibrary() {
 646     if (hSplashLib) {
 647         FreeLibrary(hSplashLib);
 648         hSplashLib = NULL;
 649     }
 650 }
 651 
 652 /*
 653  * Block current thread and continue execution in a new thread
 654  */
 655 int
 656 ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void * args) {
 657     int rslt = 0;
 658     unsigned thread_id;
 659 
 660 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
 661 #define STACK_SIZE_PARAM_IS_A_RESERVATION  (0x10000)
 662 #endif
 663 
 664     /*
 665      * STACK_SIZE_PARAM_IS_A_RESERVATION is what we want, but it's not
 666      * supported on older version of Windows. Try first with the flag; and
 667      * if that fails try again without the flag. See MSDN document or HotSpot
 668      * source (os_win32.cpp) for details.
 669      */
 670     HANDLE thread_handle =
 671       (HANDLE)_beginthreadex(NULL,
 672                              (unsigned)stack_size,
 673                              continuation,
 674                              args,
 675                              STACK_SIZE_PARAM_IS_A_RESERVATION,
 676                              &thread_id);
 677     if (thread_handle == NULL) {
 678       thread_handle =
 679       (HANDLE)_beginthreadex(NULL,
 680                              (unsigned)stack_size,
 681                              continuation,
 682                              args,
 683                              0,
 684                              &thread_id);
 685     }
 686 
 687     /* AWT preloading (AFTER main thread start) */
 688 #ifdef ENABLE_AWT_PRELOAD
 689     /* D3D preloading */
 690     if (awtPreloadD3D != 0) {
 691         char *envValue;
 692         /* D3D routines checks env.var J2D_D3D if no appropriate
 693          * command line params was specified
 694          */
 695         envValue = getenv("J2D_D3D");
 696         if (envValue != NULL && JLI_StrCaseCmp(envValue, "false") == 0) {
 697             awtPreloadD3D = 0;
 698         }
 699         /* Test that AWT preloading isn't disabled by J2D_D3D_PRELOAD env.var */
 700         envValue = getenv("J2D_D3D_PRELOAD");
 701         if (envValue != NULL && JLI_StrCaseCmp(envValue, "false") == 0) {
 702             awtPreloadD3D = 0;
 703         }
 704         if (awtPreloadD3D < 0) {
 705             /* If awtPreloadD3D is still undefined (-1), test
 706              * if it is turned on by J2D_D3D_PRELOAD env.var.
 707              * By default it's turned OFF.
 708              */
 709             awtPreloadD3D = 0;
 710             if (envValue != NULL && JLI_StrCaseCmp(envValue, "true") == 0) {
 711                 awtPreloadD3D = 1;
 712             }
 713          }
 714     }
 715     if (awtPreloadD3D) {
 716         AWTPreload(D3D_PRELOAD_FUNC);
 717     }
 718 #endif /* ENABLE_AWT_PRELOAD */
 719 
 720     if (thread_handle) {
 721       WaitForSingleObject(thread_handle, INFINITE);
 722       GetExitCodeThread(thread_handle, &rslt);
 723       CloseHandle(thread_handle);
 724     } else {
 725       rslt = continuation(args);
 726     }
 727 
 728 #ifdef ENABLE_AWT_PRELOAD
 729     if (awtPreloaded) {
 730         AWTPreloadStop();
 731     }
 732 #endif /* ENABLE_AWT_PRELOAD */
 733 
 734     return rslt;
 735 }
 736 
 737 /* Unix only, empty on windows. */
 738 void SetJavaLauncherPlatformProps() {}
 739 
 740 /*
 741  * The implementation for finding classes from the bootstrap
 742  * class loader, refer to java.h
 743  */
 744 static FindClassFromBootLoader_t *findBootClass = NULL;
 745 
 746 jclass FindBootStrapClass(JNIEnv *env, const char *classname)
 747 {
 748    HMODULE hJvm;
 749 
 750    if (findBootClass == NULL) {
 751        hJvm = GetModuleHandle(JVM_DLL);
 752        if (hJvm == NULL) return NULL;
 753        /* need to use the demangled entry point */
 754        findBootClass = (FindClassFromBootLoader_t *)GetProcAddress(hJvm,
 755             "JVM_FindClassFromBootLoader");
 756        if (findBootClass == NULL) {
 757           JLI_ReportErrorMessage(DLL_ERROR4, "JVM_FindClassFromBootLoader");
 758           return NULL;
 759        }
 760    }
 761    return findBootClass(env, classname);
 762 }
 763 
 764 void
 765 InitLauncher(boolean javaw)
 766 {
 767     INITCOMMONCONTROLSEX icx;
 768 
 769     /*
 770      * Required for javaw mode MessageBox output as well as for
 771      * HotSpot -XX:+ShowMessageBoxOnError in java mode, an empty
 772      * flag field is sufficient to perform the basic UI initialization.
 773      */
 774     memset(&icx, 0, sizeof(INITCOMMONCONTROLSEX));
 775     icx.dwSize = sizeof(INITCOMMONCONTROLSEX);
 776     InitCommonControlsEx(&icx);
 777     _isjavaw = javaw;
 778     JLI_SetTraceLauncher();
 779 }
 780 
 781 
 782 /* ============================== */
 783 /* AWT preloading */
 784 #ifdef ENABLE_AWT_PRELOAD
 785 
 786 typedef int FnPreloadStart(void);
 787 typedef void FnPreloadStop(void);
 788 static FnPreloadStop *fnPreloadStop = NULL;
 789 static HMODULE hPreloadAwt = NULL;
 790 
 791 /*
 792  * Starts AWT preloading
 793  */
 794 int AWTPreload(const char *funcName)
 795 {
 796     int result = -1;
 797     /* load AWT library once (if several preload function should be called) */
 798     if (hPreloadAwt == NULL) {
 799         /* awt.dll is not loaded yet */
 800         char libraryPath[MAXPATHLEN];
 801         size_t jrePathLen = 0;
 802         HMODULE hJava = NULL;
 803         HMODULE hVerify = NULL;
 804 
 805         while (1) {
 806             /* awt.dll depends on jvm.dll & java.dll;
 807              * jvm.dll is already loaded, so we need only java.dll;
 808              * java.dll depends on MSVCRT lib & verify.dll.
 809              */
 810             if (!GetJREPath(libraryPath, MAXPATHLEN)) {
 811                 break;
 812             }
 813 
 814             /* save path length */
 815             jrePathLen = JLI_StrLen(libraryPath);
 816 
 817             if (jrePathLen + JLI_StrLen("\\bin\\verify.dll") >= MAXPATHLEN) {
 818               /* jre path is too long, the library path will not fit there;
 819                * report and abort preloading
 820                */
 821               JLI_ReportErrorMessage(JRE_ERROR11);
 822               break;
 823             }
 824 
 825             /* load msvcrt 1st */
 826             LoadMSVCRT();
 827 
 828             /* load verify.dll */
 829             JLI_StrCat(libraryPath, "\\bin\\verify.dll");
 830             hVerify = LoadLibrary(libraryPath);
 831             if (hVerify == NULL) {
 832                 break;
 833             }
 834 
 835             /* restore jrePath */
 836             libraryPath[jrePathLen] = 0;
 837             /* load java.dll */
 838             JLI_StrCat(libraryPath, "\\bin\\" JAVA_DLL);
 839             hJava = LoadLibrary(libraryPath);
 840             if (hJava == NULL) {
 841                 break;
 842             }
 843 
 844             /* restore jrePath */
 845             libraryPath[jrePathLen] = 0;
 846             /* load awt.dll */
 847             JLI_StrCat(libraryPath, "\\bin\\awt.dll");
 848             hPreloadAwt = LoadLibrary(libraryPath);
 849             if (hPreloadAwt == NULL) {
 850                 break;
 851             }
 852 
 853             /* get "preloadStop" func ptr */
 854             fnPreloadStop = (FnPreloadStop *)GetProcAddress(hPreloadAwt, "preloadStop");
 855 
 856             break;
 857         }
 858     }
 859 
 860     if (hPreloadAwt != NULL) {
 861         FnPreloadStart *fnInit = (FnPreloadStart *)GetProcAddress(hPreloadAwt, funcName);
 862         if (fnInit != NULL) {
 863             /* don't forget to stop preloading */
 864             awtPreloaded = 1;
 865 
 866             result = fnInit();
 867         }
 868     }
 869 
 870     return result;
 871 }
 872 
 873 /*
 874  * Terminates AWT preloading
 875  */
 876 void AWTPreloadStop() {
 877     if (fnPreloadStop != NULL) {
 878         fnPreloadStop();
 879     }
 880 }
 881 
 882 #endif /* ENABLE_AWT_PRELOAD */
 883 
 884 int
 885 JVMInit(InvocationFunctions* ifn, jlong threadStackSize,
 886         int argc, char **argv,
 887         int mode, char *what, int ret)
 888 {
 889     ShowSplashScreen();
 890     return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret);
 891 }
 892 
 893 void
 894 PostJVMInit(JNIEnv *env, jclass mainClass, JavaVM *vm)
 895 {
 896     // stubbed out for windows and *nixes.
 897 }
 898 
 899 void
 900 RegisterThread()
 901 {
 902     // stubbed out for windows and *nixes.
 903 }
 904 
 905 /*
 906  * on windows, we return a false to indicate this option is not applicable
 907  */
 908 jboolean
 909 ProcessPlatformOption(const char *arg)
 910 {
 911     return JNI_FALSE;
 912 }
 913 
 914 /*
 915  * At this point we have the arguments to the application, and we need to
 916  * check with original stdargs in order to compare which of these truly
 917  * needs expansion. cmdtoargs will specify this if it finds a bare
 918  * (unquoted) argument containing a glob character(s) ie. * or ?
 919  */
 920 jobjectArray
 921 CreateApplicationArgs(JNIEnv *env, char **strv, int argc)
 922 {
 923     int i, j, idx;
 924     size_t tlen;
 925     jobjectArray outArray, inArray;
 926     char *arg, **nargv;
 927     jboolean needs_expansion = JNI_FALSE;
 928     jmethodID mid;
 929     int stdargc;
 930     StdArg *stdargs;
 931     int *appArgIdx;
 932     int isTool;
 933     jclass cls = GetLauncherHelperClass(env);
 934     NULL_CHECK0(cls);
 935 
 936     if (argc == 0) {
 937         return NewPlatformStringArray(env, strv, argc);
 938     }
 939     // the holy grail we need to compare with.
 940     stdargs = JLI_GetStdArgs();
 941     stdargc = JLI_GetStdArgc();
 942 
 943     // sanity check, this should never happen
 944     if (argc > stdargc) {
 945         JLI_TraceLauncher("Warning: app args is larger than the original, %d %d\n", argc, stdargc);
 946         JLI_TraceLauncher("passing arguments as-is.\n");
 947         return NewPlatformStringArray(env, strv, argc);
 948     }
 949 
 950     // sanity check, match the args we have, to the holy grail
 951     idx = JLI_GetAppArgIndex();
 952     isTool = (idx == 0);
 953     if (isTool) { idx++; } // skip tool name
 954     JLI_TraceLauncher("AppArgIndex: %d points to %s\n", idx, stdargs[idx].arg);
 955 
 956     appArgIdx = calloc(argc, sizeof(int));
 957     for (i = idx, j = 0; i < stdargc; i++) {
 958         if (isTool) { // filter -J used by tools to pass JVM options
 959             arg = stdargs[i].arg;
 960             if (arg[0] == '-' && arg[1] == 'J') {
 961                 continue;
 962             }
 963         }
 964         appArgIdx[j++] = i;
 965     }
 966     // sanity check, ensure same number of arguments for application
 967     if (j != argc) {
 968         JLI_TraceLauncher("Warning: app args count doesn't match, %d %d\n", j, argc);
 969         JLI_TraceLauncher("passing arguments as-is.\n");
 970         JLI_MemFree(appArgIdx);
 971         return NewPlatformStringArray(env, strv, argc);
 972     }
 973 
 974     // make a copy of the args which will be expanded in java if required.
 975     nargv = (char **)JLI_MemAlloc(argc * sizeof(char*));
 976     for (i = 0; i < argc; i++) {
 977         jboolean arg_expand;
 978         j = appArgIdx[i];
 979         arg_expand = (JLI_StrCmp(stdargs[j].arg, strv[i]) == 0)
 980             ? stdargs[j].has_wildcard
 981             : JNI_FALSE;
 982         if (needs_expansion == JNI_FALSE)
 983             needs_expansion = arg_expand;
 984 
 985         // indicator char + String + NULL terminator, the java method will strip
 986         // out the first character, the indicator character, so no matter what
 987         // we add the indicator
 988         tlen = 1 + JLI_StrLen(strv[i]) + 1;
 989         nargv[i] = (char *) JLI_MemAlloc(tlen);
 990         if (JLI_Snprintf(nargv[i], tlen, "%c%s", arg_expand ? 'T' : 'F',
 991                          strv[i]) < 0) {
 992             return NULL;
 993         }
 994         JLI_TraceLauncher("%s\n", nargv[i]);
 995     }
 996 
 997     if (!needs_expansion) {
 998         // clean up any allocated memory and return back the old arguments
 999         for (i = 0 ; i < argc ; i++) {
1000             JLI_MemFree(nargv[i]);
1001         }
1002         JLI_MemFree(nargv);
1003         JLI_MemFree(appArgIdx);
1004         return NewPlatformStringArray(env, strv, argc);
1005     }
1006     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1007                                                 "expandArgs",
1008                                                 "([Ljava/lang/String;)[Ljava/lang/String;"));
1009 
1010     // expand the arguments that require expansion, the java method will strip
1011     // out the indicator character.
1012     NULL_CHECK0(inArray = NewPlatformStringArray(env, nargv, argc));
1013     outArray = (*env)->CallStaticObjectMethod(env, cls, mid, inArray);
1014     for (i = 0; i < argc; i++) {
1015         JLI_MemFree(nargv[i]);
1016     }
1017     JLI_MemFree(nargv);
1018     JLI_MemFree(appArgIdx);
1019     return outArray;
1020 }