1 /*
   2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #include <windows.h>
  27 #include <io.h>
  28 #include <process.h>
  29 #include <stdlib.h>
  30 #include <stdio.h>
  31 #include <stdarg.h>
  32 #include <string.h>
  33 #include <sys/types.h>
  34 #include <sys/stat.h>
  35 #include <wtypes.h>
  36 #include <commctrl.h>
  37 
  38 #include <jni.h>
  39 #include "java.h"
  40 
  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 /* We supports warmup for UI stack that is performed in parallel
  52  * to VM initialization.
  53  * This helps to improve startup of UI application as warmup phase
  54  * might be long due to initialization of OS or hardware resources.
  55  * It is not CPU bound and therefore it does not interfere with VM init.
  56  * Obviously such warmup only has sense for UI apps and therefore it needs
  57  * to be explicitly requested by passing -Dsun.awt.warmup=true property
  58  * (this is always the case for plugin/javaws).
  59  *
  60  * Implementation launches new thread after VM starts and use it to perform
  61  * warmup code (platform dependent).
  62  * This thread is later reused as AWT toolkit thread as graphics toolkit
  63  * often assume that they are used from the same thread they were launched on.
  64  *
  65  * At the moment we only support warmup for D3D. It only possible on windows
  66  * and only if other flags do not prohibit this (e.g. OpenGL support requested).
  67  */
  68 #undef ENABLE_AWT_PRELOAD
  69 #ifndef JAVA_ARGS /* turn off AWT preloading for javac, jar, etc */
  70     /* CR6999872: fastdebug crashes if awt library is loaded before JVM is
  71      * initialized*/
  72     #if !defined(DEBUG)
  73         #define ENABLE_AWT_PRELOAD
  74     #endif
  75 #endif
  76 
  77 #ifdef ENABLE_AWT_PRELOAD
  78 /* "AWT was preloaded" flag;
  79  * turned on by AWTPreload().
  80  */
  81 int awtPreloaded = 0;
  82 
  83 /* Calls a function with the name specified
  84  * the function must be int(*fn)(void).
  85  */
  86 int AWTPreload(const char *funcName);
  87 /* stops AWT preloading */
  88 void AWTPreloadStop();
  89 
  90 /* D3D preloading */
  91 /* -1: not initialized; 0: OFF, 1: ON */
  92 int awtPreloadD3D = -1;
  93 /* command line parameter to swith D3D preloading on */
  94 #define PARAM_PRELOAD_D3D "-Dsun.awt.warmup"
  95 /* D3D/OpenGL management parameters */
  96 #define PARAM_NODDRAW "-Dsun.java2d.noddraw"
  97 #define PARAM_D3D "-Dsun.java2d.d3d"
  98 #define PARAM_OPENGL "-Dsun.java2d.opengl"
  99 /* funtion in awt.dll (src/windows/native/sun/java2d/d3d/D3DPipelineManager.cpp) */
 100 #define D3D_PRELOAD_FUNC "preloadD3D"
 101 
 102 /* Extracts value of a parameter with the specified name
 103  * from command line argument (returns pointer in the argument).
 104  * Returns NULL if the argument does not contains the parameter.
 105  * e.g.:
 106  * GetParamValue("theParam", "theParam=value") returns pointer to "value".
 107  */
 108 const char * GetParamValue(const char *paramName, const char *arg) {
 109     size_t nameLen = JLI_StrLen(paramName);
 110     if (JLI_StrNCmp(paramName, arg, nameLen) == 0) {
 111         /* arg[nameLen] is valid (may contain final NULL) */
 112         if (arg[nameLen] == '=') {
 113             return arg + nameLen + 1;
 114         }
 115     }
 116     return NULL;
 117 }
 118 
 119 /* Checks if commandline argument contains property specified
 120  * and analyze it as boolean property (true/false).
 121  * Returns -1 if the argument does not contain the parameter;
 122  * Returns 1 if the argument contains the parameter and its value is "true";
 123  * Returns 0 if the argument contains the parameter and its value is "false".
 124  */
 125 int GetBoolParamValue(const char *paramName, const char *arg) {
 126     const char * paramValue = GetParamValue(paramName, arg);
 127     if (paramValue != NULL) {
 128         if (JLI_StrCaseCmp(paramValue, "true") == 0) {
 129             return 1;
 130         }
 131         if (JLI_StrCaseCmp(paramValue, "false") == 0) {
 132             return 0;
 133         }
 134     }
 135     return -1;
 136 }
 137 #endif /* ENABLE_AWT_PRELOAD */
 138 
 139 
 140 static jboolean _isjavaw = JNI_FALSE;
 141 
 142 
 143 jboolean
 144 IsJavaw()
 145 {
 146     return _isjavaw;
 147 }
 148 
 149 /*
 150  * Returns the arch path, to get the current arch use the
 151  * macro GetArch, nbits here is ignored for now.
 152  */
 153 const char *
 154 GetArchPath(int nbits)
 155 {
 156 #ifdef _M_AMD64
 157     return "amd64";
 158 #elif defined(_M_IA64)
 159     return "ia64";
 160 #else
 161     return "i386";
 162 #endif
 163 }
 164 
 165 /*
 166  *
 167  */
 168 void
 169 CreateExecutionEnvironment(int *pargc, char ***pargv,
 170                            char *jrepath, jint so_jrepath,
 171                            char *jvmpath, jint so_jvmpath,
 172                            char *jvmcfg,  jint so_jvmcfg) {
 173     char * jvmtype;
 174     int i = 0;
 175     int running = CURRENT_DATA_MODEL;
 176 
 177     int wanted = running;
 178 
 179     char** argv = *pargv;
 180     for (i = 1; i < *pargc ; i++) {
 181         if (JLI_StrCmp(argv[i], "-J-d64") == 0 || JLI_StrCmp(argv[i], "-d64") == 0) {
 182             wanted = 64;
 183             continue;
 184         }
 185         if (JLI_StrCmp(argv[i], "-J-d32") == 0 || JLI_StrCmp(argv[i], "-d32") == 0) {
 186             wanted = 32;
 187             continue;
 188         }
 189 
 190         if (IsJavaArgs() && argv[i][0] != '-')
 191             continue;
 192         if (argv[i][0] != '-')
 193             break;
 194     }
 195     if (running != wanted) {
 196         JLI_ReportErrorMessage(JRE_ERROR2, wanted);
 197         exit(1);
 198     }
 199 
 200     /* Find out where the JRE is that we will be using. */
 201     if (!GetJREPath(jrepath, so_jrepath)) {
 202         JLI_ReportErrorMessage(JRE_ERROR1);
 203         exit(2);
 204     }
 205 
 206     JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%s%s%sjvm.cfg",
 207         jrepath, FILESEP, FILESEP, (char*)GetArch(), FILESEP);
 208 
 209     /* Find the specified JVM type */
 210     if (ReadKnownVMs(jvmcfg, JNI_FALSE) < 1) {
 211         JLI_ReportErrorMessage(CFG_ERROR7);
 212         exit(1);
 213     }
 214 
 215     jvmtype = CheckJvmType(pargc, pargv, JNI_FALSE);
 216     if (JLI_StrCmp(jvmtype, "ERROR") == 0) {
 217         JLI_ReportErrorMessage(CFG_ERROR9);
 218         exit(4);
 219     }
 220 
 221     jvmpath[0] = '\0';
 222     if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath)) {
 223         JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath);
 224         exit(4);
 225     }
 226     /* If we got here, jvmpath has been correctly initialized. */
 227 
 228     /* Check if we need preload AWT */
 229 #ifdef ENABLE_AWT_PRELOAD
 230     argv = *pargv;
 231     for (i = 0; i < *pargc ; i++) {
 232         /* Tests the "turn on" parameter only if not set yet. */
 233         if (awtPreloadD3D < 0) {
 234             if (GetBoolParamValue(PARAM_PRELOAD_D3D, argv[i]) == 1) {
 235                 awtPreloadD3D = 1;
 236             }
 237         }
 238         /* Test parameters which can disable preloading if not already disabled. */
 239         if (awtPreloadD3D != 0) {
 240             if (GetBoolParamValue(PARAM_NODDRAW, argv[i]) == 1
 241                 || GetBoolParamValue(PARAM_D3D, argv[i]) == 0
 242                 || GetBoolParamValue(PARAM_OPENGL, argv[i]) == 1)
 243             {
 244                 awtPreloadD3D = 0;
 245                 /* no need to test the rest of the parameters */
 246                 break;
 247             }
 248         }
 249     }
 250 #endif /* ENABLE_AWT_PRELOAD */
 251 }
 252 
 253 
 254 static jboolean
 255 LoadMSVCRT()
 256 {
 257     // Only do this once
 258     static int loaded = 0;
 259     char crtpath[MAXPATHLEN];
 260 
 261     if (!loaded) {
 262         /*
 263          * The Microsoft C Runtime Library needs to be loaded first.  A copy is
 264          * assumed to be present in the "JRE path" directory.  If it is not found
 265          * there (or "JRE path" fails to resolve), skip the explicit load and let
 266          * nature take its course, which is likely to be a failure to execute.
 267          * The makefiles will provide the correct lib contained in quotes in the
 268          * macro MSVCR_DLL_NAME.
 269          */
 270 #ifdef MSVCR_DLL_NAME
 271         if (GetJREPath(crtpath, MAXPATHLEN)) {
 272             if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") +
 273                     JLI_StrLen(MSVCR_DLL_NAME) >= MAXPATHLEN) {
 274                 JLI_ReportErrorMessage(JRE_ERROR11);
 275                 return JNI_FALSE;
 276             }
 277             (void)JLI_StrCat(crtpath, "\\bin\\" MSVCR_DLL_NAME);   /* Add crt dll */
 278             JLI_TraceLauncher("CRT path is %s\n", crtpath);
 279             if (_access(crtpath, 0) == 0) {
 280                 if (LoadLibrary(crtpath) == 0) {
 281                     JLI_ReportErrorMessage(DLL_ERROR4, crtpath);
 282                     return JNI_FALSE;
 283                 }
 284             }
 285         }
 286 #endif /* MSVCR_DLL_NAME */
 287 #ifdef MSVCP_DLL_NAME
 288         if (GetJREPath(crtpath, MAXPATHLEN)) {
 289             if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") +
 290                     JLI_StrLen(MSVCP_DLL_NAME) >= MAXPATHLEN) {
 291                 JLI_ReportErrorMessage(JRE_ERROR11);
 292                 return JNI_FALSE;
 293             }
 294             (void)JLI_StrCat(crtpath, "\\bin\\" MSVCP_DLL_NAME);   /* Add prt dll */
 295             JLI_TraceLauncher("PRT path is %s\n", crtpath);
 296             if (_access(crtpath, 0) == 0) {
 297                 if (LoadLibrary(crtpath) == 0) {
 298                     JLI_ReportErrorMessage(DLL_ERROR4, crtpath);
 299                     return JNI_FALSE;
 300                 }
 301             }
 302         }
 303 #endif /* MSVCP_DLL_NAME */
 304         loaded = 1;
 305     }
 306     return JNI_TRUE;
 307 }
 308 
 309 
 310 /*
 311  * Find path to JRE based on .exe's location or registry settings.
 312  */
 313 jboolean
 314 GetJREPath(char *path, jint pathsize)
 315 {
 316     char javadll[MAXPATHLEN];
 317     struct stat s;
 318 
 319     if (GetApplicationHome(path, pathsize)) {
 320         /* Is JRE co-located with the application? */
 321         JLI_Snprintf(javadll, sizeof(javadll), "%s\\bin\\" JAVA_DLL, path);
 322         if (stat(javadll, &s) == 0) {
 323             JLI_TraceLauncher("JRE path is %s\n", path);
 324             return JNI_TRUE;
 325         }
 326 
 327         /* Does this app ship a private JRE in <apphome>\jre directory? */
 328         JLI_Snprintf(javadll, sizeof (javadll), "%s\\jre\\bin\\" JAVA_DLL, path);
 329         if (stat(javadll, &s) == 0) {
 330             JLI_StrCat(path, "\\jre");
 331             JLI_TraceLauncher("JRE path is %s\n", path);
 332             return JNI_TRUE;
 333         }
 334     }
 335 
 336     JLI_ReportErrorMessage(JRE_ERROR8 JAVA_DLL);
 337     return JNI_FALSE;
 338 
 339 }
 340 
 341 /*
 342  * Given a JRE location and a JVM type, construct what the name the
 343  * JVM shared library will be.  Return true, if such a library
 344  * exists, false otherwise.
 345  */
 346 static jboolean
 347 GetJVMPath(const char *jrepath, const char *jvmtype,
 348            char *jvmpath, jint jvmpathsize)
 349 {
 350     struct stat s;
 351     if (JLI_StrChr(jvmtype, '/') || JLI_StrChr(jvmtype, '\\')) {
 352         JLI_Snprintf(jvmpath, jvmpathsize, "%s\\" JVM_DLL, jvmtype);
 353     } else {
 354         JLI_Snprintf(jvmpath, jvmpathsize, "%s\\bin\\%s\\" JVM_DLL,
 355                      jrepath, jvmtype);
 356     }
 357     if (stat(jvmpath, &s) == 0) {
 358         return JNI_TRUE;
 359     } else {
 360         return JNI_FALSE;
 361     }
 362 }
 363 
 364 /*
 365  * Load a jvm from "jvmpath" and initialize the invocation functions.
 366  */
 367 jboolean
 368 LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)
 369 {
 370     HINSTANCE handle;
 371 
 372     JLI_TraceLauncher("JVM path is %s\n", jvmpath);
 373 
 374     /*
 375      * The Microsoft C Runtime Library needs to be loaded first.  A copy is
 376      * assumed to be present in the "JRE path" directory.  If it is not found
 377      * there (or "JRE path" fails to resolve), skip the explicit load and let
 378      * nature take its course, which is likely to be a failure to execute.
 379      *
 380      */
 381     LoadMSVCRT();
 382 
 383     /* Load the Java VM DLL */
 384     if ((handle = LoadLibrary(jvmpath)) == 0) {
 385         JLI_ReportErrorMessage(DLL_ERROR4, (char *)jvmpath);
 386         return JNI_FALSE;
 387     }
 388 
 389     /* Now get the function addresses */
 390     ifn->CreateJavaVM =
 391         (void *)GetProcAddress(handle, "JNI_CreateJavaVM");
 392     ifn->GetDefaultJavaVMInitArgs =
 393         (void *)GetProcAddress(handle, "JNI_GetDefaultJavaVMInitArgs");
 394     if (ifn->CreateJavaVM == 0 || ifn->GetDefaultJavaVMInitArgs == 0) {
 395         JLI_ReportErrorMessage(JNI_ERROR1, (char *)jvmpath);
 396         return JNI_FALSE;
 397     }
 398 
 399     return JNI_TRUE;
 400 }
 401 
 402 /*
 403  * If app is "c:\foo\bin\javac", then put "c:\foo" into buf.
 404  */
 405 jboolean
 406 GetApplicationHome(char *buf, jint bufsize)
 407 {
 408     char *cp;
 409     GetModuleFileName(0, buf, bufsize);
 410     *JLI_StrRChr(buf, '\\') = '\0'; /* remove .exe file name */
 411     if ((cp = JLI_StrRChr(buf, '\\')) == 0) {
 412         /* This happens if the application is in a drive root, and
 413          * there is no bin directory. */
 414         buf[0] = '\0';
 415         return JNI_FALSE;
 416     }
 417     *cp = '\0';  /* remove the bin\ part */
 418     return JNI_TRUE;
 419 }
 420 
 421 /*
 422  * Support for doing cheap, accurate interval timing.
 423  */
 424 static jboolean counterAvailable = JNI_FALSE;
 425 static jboolean counterInitialized = JNI_FALSE;
 426 static LARGE_INTEGER counterFrequency;
 427 
 428 jlong CounterGet()
 429 {
 430     LARGE_INTEGER count;
 431 
 432     if (!counterInitialized) {
 433         counterAvailable = QueryPerformanceFrequency(&counterFrequency);
 434         counterInitialized = JNI_TRUE;
 435     }
 436     if (!counterAvailable) {
 437         return 0;
 438     }
 439     QueryPerformanceCounter(&count);
 440     return (jlong)(count.QuadPart);
 441 }
 442 
 443 jlong Counter2Micros(jlong counts)
 444 {
 445     if (!counterAvailable || !counterInitialized) {
 446         return 0;
 447     }
 448     return (counts * 1000 * 1000)/counterFrequency.QuadPart;
 449 }
 450 /*
 451  * windows snprintf does not guarantee a null terminator in the buffer,
 452  * if the computed size is equal to or greater than the buffer size,
 453  * as well as error conditions. This function guarantees a null terminator
 454  * under all these conditions. An unreasonable buffer or size will return
 455  * an error value. Under all other conditions this function will return the
 456  * size of the bytes actually written minus the null terminator, similar
 457  * to ansi snprintf api. Thus when calling this function the caller must
 458  * ensure storage for the null terminator.
 459  */
 460 int
 461 JLI_Snprintf(char* buffer, size_t size, const char* format, ...) {
 462     int rc;
 463     va_list vl;
 464     if (size == 0 || buffer == NULL)
 465         return -1;
 466     buffer[0] = '\0';
 467     va_start(vl, format);
 468     rc = vsnprintf(buffer, size, format, vl);
 469     va_end(vl);
 470     /* force a null terminator, if something is amiss */
 471     if (rc < 0) {
 472         /* apply ansi semantics */
 473         buffer[size - 1] = '\0';
 474         return (int)size;
 475     } else if (rc == size) {
 476         /* force a null terminator */
 477         buffer[size - 1] = '\0';
 478     }
 479     return rc;
 480 }
 481 
 482 void
 483 JLI_ReportErrorMessage(const char* fmt, ...) {
 484     va_list vl;
 485     va_start(vl,fmt);
 486 
 487     if (IsJavaw()) {
 488         char *message;
 489 
 490         /* get the length of the string we need */
 491         int n = _vscprintf(fmt, vl);
 492 
 493         message = (char *)JLI_MemAlloc(n + 1);
 494         _vsnprintf(message, n, fmt, vl);
 495         message[n]='\0';
 496         MessageBox(NULL, message, "Java Virtual Machine Launcher",
 497             (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
 498         JLI_MemFree(message);
 499     } else {
 500         vfprintf(stderr, fmt, vl);
 501         fprintf(stderr, "\n");
 502     }
 503     va_end(vl);
 504 }
 505 
 506 /*
 507  * Just like JLI_ReportErrorMessage, except that it concatenates the system
 508  * error message if any, its upto the calling routine to correctly
 509  * format the separation of the messages.
 510  */
 511 void
 512 JLI_ReportErrorMessageSys(const char *fmt, ...)
 513 {
 514     va_list vl;
 515 
 516     int save_errno = errno;
 517     DWORD       errval;
 518     jboolean freeit = JNI_FALSE;
 519     char  *errtext = NULL;
 520 
 521     va_start(vl, fmt);
 522 
 523     if ((errval = GetLastError()) != 0) {               /* Platform SDK / DOS Error */
 524         int n = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|
 525             FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_ALLOCATE_BUFFER,
 526             NULL, errval, 0, (LPTSTR)&errtext, 0, NULL);
 527         if (errtext == NULL || n == 0) {                /* Paranoia check */
 528             errtext = "";
 529             n = 0;
 530         } else {
 531             freeit = JNI_TRUE;
 532             if (n > 2) {                                /* Drop final CR, LF */
 533                 if (errtext[n - 1] == '\n') n--;
 534                 if (errtext[n - 1] == '\r') n--;
 535                 errtext[n] = '\0';
 536             }
 537         }
 538     } else {   /* C runtime error that has no corresponding DOS error code */
 539         errtext = strerror(save_errno);
 540     }
 541 
 542     if (IsJavaw()) {
 543         char *message;
 544         int mlen;
 545         /* get the length of the string we need */
 546         int len = mlen =  _vscprintf(fmt, vl) + 1;
 547         if (freeit) {
 548            mlen += (int)JLI_StrLen(errtext);
 549         }
 550 
 551         message = (char *)JLI_MemAlloc(mlen);
 552         _vsnprintf(message, len, fmt, vl);
 553         message[len]='\0';
 554 
 555         if (freeit) {
 556            JLI_StrCat(message, errtext);
 557         }
 558 
 559         MessageBox(NULL, message, "Java Virtual Machine Launcher",
 560             (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
 561 
 562         JLI_MemFree(message);
 563     } else {
 564         vfprintf(stderr, fmt, vl);
 565         if (freeit) {
 566            fprintf(stderr, "%s", errtext);
 567         }
 568     }
 569     if (freeit) {
 570         (void)LocalFree((HLOCAL)errtext);
 571     }
 572     va_end(vl);
 573 }
 574 
 575 void  JLI_ReportExceptionDescription(JNIEnv * env) {
 576     if (IsJavaw()) {
 577        /*
 578         * This code should be replaced by code which opens a window with
 579         * the exception detail message, for now atleast put a dialog up.
 580         */
 581         MessageBox(NULL, "A Java Exception has occurred.", "Java Virtual Machine Launcher",
 582                (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
 583     } else {
 584         (*env)->ExceptionDescribe(env);
 585     }
 586 }
 587 
 588 jboolean
 589 ServerClassMachine() {
 590     return (GetErgoPolicy() == ALWAYS_SERVER_CLASS) ? JNI_TRUE : JNI_FALSE;
 591 }
 592 
 593 /*
 594  * Wrapper for platform dependent unsetenv function.
 595  */
 596 int
 597 UnsetEnv(char *name)
 598 {
 599     int ret;
 600     char *buf = JLI_MemAlloc(JLI_StrLen(name) + 2);
 601     buf = JLI_StrCat(JLI_StrCpy(buf, name), "=");
 602     ret = _putenv(buf);
 603     JLI_MemFree(buf);
 604     return (ret);
 605 }
 606 
 607 /* --- Splash Screen shared library support --- */
 608 
 609 static const char* SPLASHSCREEN_SO = "\\bin\\splashscreen.dll";
 610 
 611 static HMODULE hSplashLib = NULL;
 612 
 613 void* SplashProcAddress(const char* name) {
 614     char libraryPath[MAXPATHLEN]; /* some extra space for JLI_StrCat'ing SPLASHSCREEN_SO */
 615 
 616     if (!GetJREPath(libraryPath, MAXPATHLEN)) {
 617         return NULL;
 618     }
 619     if (JLI_StrLen(libraryPath)+JLI_StrLen(SPLASHSCREEN_SO) >= MAXPATHLEN) {
 620         return NULL;
 621     }
 622     JLI_StrCat(libraryPath, SPLASHSCREEN_SO);
 623 
 624     if (!hSplashLib) {
 625         hSplashLib = LoadLibrary(libraryPath);
 626     }
 627     if (hSplashLib) {
 628         return GetProcAddress(hSplashLib, name);
 629     } else {
 630         return NULL;
 631     }
 632 }
 633 
 634 void SplashFreeLibrary() {
 635     if (hSplashLib) {
 636         FreeLibrary(hSplashLib);
 637         hSplashLib = NULL;
 638     }
 639 }
 640 
 641 /*
 642  * Block current thread and continue execution in a new thread
 643  */
 644 int
 645 ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void * args) {
 646     int rslt = 0;
 647     unsigned thread_id;
 648 
 649 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
 650 #define STACK_SIZE_PARAM_IS_A_RESERVATION  (0x10000)
 651 #endif
 652 
 653     /*
 654      * STACK_SIZE_PARAM_IS_A_RESERVATION is what we want, but it's not
 655      * supported on older version of Windows. Try first with the flag; and
 656      * if that fails try again without the flag. See MSDN document or HotSpot
 657      * source (os_win32.cpp) for details.
 658      */
 659     HANDLE thread_handle =
 660       (HANDLE)_beginthreadex(NULL,
 661                              (unsigned)stack_size,
 662                              continuation,
 663                              args,
 664                              STACK_SIZE_PARAM_IS_A_RESERVATION,
 665                              &thread_id);
 666     if (thread_handle == NULL) {
 667       thread_handle =
 668       (HANDLE)_beginthreadex(NULL,
 669                              (unsigned)stack_size,
 670                              continuation,
 671                              args,
 672                              0,
 673                              &thread_id);
 674     }
 675 
 676     /* AWT preloading (AFTER main thread start) */
 677 #ifdef ENABLE_AWT_PRELOAD
 678     /* D3D preloading */
 679     if (awtPreloadD3D != 0) {
 680         char *envValue;
 681         /* D3D routines checks env.var J2D_D3D if no appropriate
 682          * command line params was specified
 683          */
 684         envValue = getenv("J2D_D3D");
 685         if (envValue != NULL && JLI_StrCaseCmp(envValue, "false") == 0) {
 686             awtPreloadD3D = 0;
 687         }
 688         /* Test that AWT preloading isn't disabled by J2D_D3D_PRELOAD env.var */
 689         envValue = getenv("J2D_D3D_PRELOAD");
 690         if (envValue != NULL && JLI_StrCaseCmp(envValue, "false") == 0) {
 691             awtPreloadD3D = 0;
 692         }
 693         if (awtPreloadD3D < 0) {
 694             /* If awtPreloadD3D is still undefined (-1), test
 695              * if it is turned on by J2D_D3D_PRELOAD env.var.
 696              * By default it's turned OFF.
 697              */
 698             awtPreloadD3D = 0;
 699             if (envValue != NULL && JLI_StrCaseCmp(envValue, "true") == 0) {
 700                 awtPreloadD3D = 1;
 701             }
 702          }
 703     }
 704     if (awtPreloadD3D) {
 705         AWTPreload(D3D_PRELOAD_FUNC);
 706     }
 707 #endif /* ENABLE_AWT_PRELOAD */
 708 
 709     if (thread_handle) {
 710       WaitForSingleObject(thread_handle, INFINITE);
 711       GetExitCodeThread(thread_handle, &rslt);
 712       CloseHandle(thread_handle);
 713     } else {
 714       rslt = continuation(args);
 715     }
 716 
 717 #ifdef ENABLE_AWT_PRELOAD
 718     if (awtPreloaded) {
 719         AWTPreloadStop();
 720     }
 721 #endif /* ENABLE_AWT_PRELOAD */
 722 
 723     return rslt;
 724 }
 725 
 726 /* Unix only, empty on windows. */
 727 void SetJavaLauncherPlatformProps() {}
 728 
 729 /*
 730  * The implementation for finding classes from the bootstrap
 731  * class loader, refer to java.h
 732  */
 733 static FindClassFromBootLoader_t *findBootClass = NULL;
 734 
 735 jclass FindBootStrapClass(JNIEnv *env, const char *classname)
 736 {
 737    HMODULE hJvm;
 738 
 739    if (findBootClass == NULL) {
 740        hJvm = GetModuleHandle(JVM_DLL);
 741        if (hJvm == NULL) return NULL;
 742        /* need to use the demangled entry point */
 743        findBootClass = (FindClassFromBootLoader_t *)GetProcAddress(hJvm,
 744             "JVM_FindClassFromBootLoader");
 745        if (findBootClass == NULL) {
 746           JLI_ReportErrorMessage(DLL_ERROR4, "JVM_FindClassFromBootLoader");
 747           return NULL;
 748        }
 749    }
 750    return findBootClass(env, classname);
 751 }
 752 
 753 void
 754 InitLauncher(boolean javaw)
 755 {
 756     INITCOMMONCONTROLSEX icx;
 757 
 758     /*
 759      * Required for javaw mode MessageBox output as well as for
 760      * HotSpot -XX:+ShowMessageBoxOnError in java mode, an empty
 761      * flag field is sufficient to perform the basic UI initialization.
 762      */
 763     memset(&icx, 0, sizeof(INITCOMMONCONTROLSEX));
 764     icx.dwSize = sizeof(INITCOMMONCONTROLSEX);
 765     InitCommonControlsEx(&icx);
 766     _isjavaw = javaw;
 767     JLI_SetTraceLauncher();
 768 }
 769 
 770 
 771 /* ============================== */
 772 /* AWT preloading */
 773 #ifdef ENABLE_AWT_PRELOAD
 774 
 775 typedef int FnPreloadStart(void);
 776 typedef void FnPreloadStop(void);
 777 static FnPreloadStop *fnPreloadStop = NULL;
 778 static HMODULE hPreloadAwt = NULL;
 779 
 780 /*
 781  * Starts AWT preloading
 782  */
 783 int AWTPreload(const char *funcName)
 784 {
 785     int result = -1;
 786     /* load AWT library once (if several preload function should be called) */
 787     if (hPreloadAwt == NULL) {
 788         /* awt.dll is not loaded yet */
 789         char libraryPath[MAXPATHLEN];
 790         size_t jrePathLen = 0;
 791         HMODULE hJava = NULL;
 792         HMODULE hVerify = NULL;
 793 
 794         while (1) {
 795             /* awt.dll depends on jvm.dll & java.dll;
 796              * jvm.dll is already loaded, so we need only java.dll;
 797              * java.dll depends on MSVCRT lib & verify.dll.
 798              */
 799             if (!GetJREPath(libraryPath, MAXPATHLEN)) {
 800                 break;
 801             }
 802 
 803             /* save path length */
 804             jrePathLen = JLI_StrLen(libraryPath);
 805 
 806             if (jrePathLen + JLI_StrLen("\\bin\\verify.dll") >= MAXPATHLEN) {
 807               /* jre path is too long, the library path will not fit there;
 808                * report and abort preloading
 809                */
 810               JLI_ReportErrorMessage(JRE_ERROR11);
 811               break;
 812             }
 813 
 814             /* load msvcrt 1st */
 815             LoadMSVCRT();
 816 
 817             /* load verify.dll */
 818             JLI_StrCat(libraryPath, "\\bin\\verify.dll");
 819             hVerify = LoadLibrary(libraryPath);
 820             if (hVerify == NULL) {
 821                 break;
 822             }
 823 
 824             /* restore jrePath */
 825             libraryPath[jrePathLen] = 0;
 826             /* load java.dll */
 827             JLI_StrCat(libraryPath, "\\bin\\" JAVA_DLL);
 828             hJava = LoadLibrary(libraryPath);
 829             if (hJava == NULL) {
 830                 break;
 831             }
 832 
 833             /* restore jrePath */
 834             libraryPath[jrePathLen] = 0;
 835             /* load awt.dll */
 836             JLI_StrCat(libraryPath, "\\bin\\awt.dll");
 837             hPreloadAwt = LoadLibrary(libraryPath);
 838             if (hPreloadAwt == NULL) {
 839                 break;
 840             }
 841 
 842             /* get "preloadStop" func ptr */
 843             fnPreloadStop = (FnPreloadStop *)GetProcAddress(hPreloadAwt, "preloadStop");
 844 
 845             break;
 846         }
 847     }
 848 
 849     if (hPreloadAwt != NULL) {
 850         FnPreloadStart *fnInit = (FnPreloadStart *)GetProcAddress(hPreloadAwt, funcName);
 851         if (fnInit != NULL) {
 852             /* don't forget to stop preloading */
 853             awtPreloaded = 1;
 854 
 855             result = fnInit();
 856         }
 857     }
 858 
 859     return result;
 860 }
 861 
 862 /*
 863  * Terminates AWT preloading
 864  */
 865 void AWTPreloadStop() {
 866     if (fnPreloadStop != NULL) {
 867         fnPreloadStop();
 868     }
 869 }
 870 
 871 #endif /* ENABLE_AWT_PRELOAD */
 872 
 873 int
 874 JVMInit(InvocationFunctions* ifn, jlong threadStackSize,
 875         int argc, char **argv,
 876         int mode, char *what, int ret)
 877 {
 878     ShowSplashScreen();
 879     return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret);
 880 }
 881 
 882 void
 883 PostJVMInit(JNIEnv *env, jclass mainClass, JavaVM *vm)
 884 {
 885     // stubbed out for windows and *nixes.
 886 }
 887 
 888 void
 889 RegisterThread()
 890 {
 891     // stubbed out for windows and *nixes.
 892 }
 893 
 894 /*
 895  * on windows, we return a false to indicate this option is not applicable
 896  */
 897 jboolean
 898 ProcessPlatformOption(const char *arg)
 899 {
 900     return JNI_FALSE;
 901 }
 902 
 903 int
 904 filterArgs(StdArg *stdargs, const int nargc, StdArg **pargv) {
 905     StdArg* argv = NULL;
 906     int nargs = 0;
 907     int i;
 908 
 909     /* Copy the non-vm args */
 910     for (i = 0; i < nargc ; i++) {
 911         const char *arg = stdargs[i].arg;
 912         if (arg[0] == '-' && arg[1] == 'J')
 913             continue;
 914         argv = (StdArg*) JLI_MemRealloc(argv, (nargs+1) * sizeof(StdArg));
 915         argv[nargs].arg = JLI_StringDup(arg);
 916         argv[nargs].has_wildcard = stdargs[i].has_wildcard;
 917         nargs++;
 918     }
 919     *pargv = argv;
 920     return nargs;
 921 }
 922 
 923 /*
 924  * At this point we have the arguments to the application, and we need to
 925  * check with original stdargs in order to compare which of these truly
 926  * needs expansion. cmdtoargs will specify this if it finds a bare
 927  * (unquoted) argument containing a glob character(s) ie. * or ?
 928  */
 929 jobjectArray
 930 CreateApplicationArgs(JNIEnv *env, char **strv, int argc)
 931 {
 932     int i, j, idx;
 933     size_t tlen;
 934     jobjectArray outArray, inArray;
 935     char *ostart, *astart, **nargv;
 936     jboolean needs_expansion = JNI_FALSE;
 937     jmethodID mid;
 938     int filteredargc, stdargc;
 939     StdArg *stdargs;
 940     StdArg *filteredargs;
 941     jclass cls = GetLauncherHelperClass(env);
 942     NULL_CHECK0(cls);
 943 
 944     if (argc == 0) {
 945         return NewPlatformStringArray(env, strv, argc);
 946     }
 947     // the holy grail we need to compare with.
 948     stdargs = JLI_GetStdArgs();
 949     stdargc = JLI_GetStdArgc();
 950 
 951     filteredargc = filterArgs(stdargs, stdargc, &filteredargs);
 952 
 953     // sanity check, this should never happen
 954     if (argc > stdargc) {
 955         JLI_TraceLauncher("Warning: app args is larger than the original, %d %d\n", argc, stdargc);
 956         JLI_TraceLauncher("passing arguments as-is.\n");
 957         return NewPlatformStringArray(env, strv, argc);
 958     }
 959 
 960     // sanity check, match the args we have, to the holy grail
 961     idx = filteredargc - argc;
 962     ostart = filteredargs[idx].arg;
 963     astart = strv[0];
 964     // sanity check, ensure that the first argument of the arrays are the same
 965     if (JLI_StrCmp(ostart, astart) != 0) {
 966         // some thing is amiss the args don't match
 967         JLI_TraceLauncher("Warning: app args parsing error\n");
 968         JLI_TraceLauncher("passing arguments as-is\n");
 969         return NewPlatformStringArray(env, strv, argc);
 970     }
 971 
 972     // make a copy of the args which will be expanded in java if required.
 973     nargv = (char **)JLI_MemAlloc(argc * sizeof(char*));
 974     for (i = 0, j = idx; i < argc; i++, j++) {
 975         jboolean arg_expand = (JLI_StrCmp(filteredargs[j].arg, strv[i]) == 0)
 976                                 ? filteredargs[j].has_wildcard
 977                                 : JNI_FALSE;
 978         if (needs_expansion == JNI_FALSE)
 979             needs_expansion = arg_expand;
 980 
 981         // indicator char + String + NULL terminator, the java method will strip
 982         // out the first character, the indicator character, so no matter what
 983         // we add the indicator
 984         tlen = 1 + JLI_StrLen(strv[i]) + 1;
 985         nargv[i] = (char *) JLI_MemAlloc(tlen);
 986         if (JLI_Snprintf(nargv[i], tlen, "%c%s", arg_expand ? 'T' : 'F',
 987                          strv[i]) < 0) {
 988             return NULL;
 989         }
 990         JLI_TraceLauncher("%s\n", nargv[i]);
 991     }
 992 
 993     if (!needs_expansion) {
 994         // clean up any allocated memory and return back the old arguments
 995         for (i = 0 ; i < argc ; i++) {
 996             JLI_MemFree(nargv[i]);
 997         }
 998         JLI_MemFree(nargv);
 999         return NewPlatformStringArray(env, strv, argc);
1000     }
1001     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1002                                                 "expandArgs",
1003                                                 "([Ljava/lang/String;)[Ljava/lang/String;"));
1004 
1005     // expand the arguments that require expansion, the java method will strip
1006     // out the indicator character.
1007     NULL_CHECK0(inArray = NewPlatformStringArray(env, nargv, argc));
1008     outArray = (*env)->CallStaticObjectMethod(env, cls, mid, inArray);
1009     for (i = 0; i < argc; i++) {
1010         JLI_MemFree(nargv[i]);
1011     }
1012     JLI_MemFree(nargv);
1013     JLI_MemFree(filteredargs);
1014     return outArray;
1015 }
1016 
1017 /*
1018  * Checks the command line arguments to find whether they are on Unicode.
1019  */
1020 static jboolean
1021 IsArgsUnicodeDecodingRequired(int argc, char **argv) {
1022     int i;
1023 
1024     if (argc < 2) {
1025         return JNI_FALSE;
1026     }
1027 
1028     for (i = 1; i < argc; ++i) {
1029         char *arg = argv[i];
1030         if (*arg != '-') {
1031             break;
1032         }
1033         if (stricmp(arg, "-Dwindows.UnicodeConsole=true") == 0) {
1034             return JNI_TRUE;
1035         }
1036     }
1037     return JNI_FALSE;
1038 }
1039 
1040 /*
1041  * Translate Unicode command line arguments to multi byte chars.
1042  */
1043 static jboolean
1044 DecodeUnicodeArgs(LPWSTR cmd_line_wide, LPSTR* cmd_line_utf8) {
1045     int cmd_line_utf8_length;
1046 
1047     // First call to WideCharToMultiByte calculates destination buffer length.
1048     cmd_line_utf8_length = WideCharToMultiByte(CP_UTF8,
1049                                             0,
1050                                             cmd_line_wide,
1051                                             -1,
1052                                             NULL,
1053                                             0,
1054                                             NULL,
1055                                             NULL);
1056     if (!cmd_line_utf8_length) {
1057         JLI_ReportErrorMessage(
1058             "WideCharToMultiByte failed to calculate destination buffer length "
1059             "with error code %d", GetLastError());
1060         return JNI_FALSE;
1061     }
1062 
1063     // Allocate buffer to receive conversion to UTF-8.
1064     *cmd_line_utf8 = JLI_MemAlloc((size_t)cmd_line_utf8_length * sizeof(CHAR));
1065 
1066     // Second call to WideCharToMultiByte does the actual conversion.  Note that
1067     // we are forcing the encoding to UTF-8.  This only works right if
1068     // getEncodingInternal in java_props_md.c also returns UTF-8.
1069     if (!WideCharToMultiByte(CP_UTF8,
1070                              0,
1071                              cmd_line_wide,
1072                              -1,
1073                              *cmd_line_utf8,
1074                              cmd_line_utf8_length,
1075                              NULL,
1076                              NULL)) {
1077         JLI_ReportErrorMessage(
1078             "WideCharToMultiByte failed to convert to UTF-8 "
1079             "with error code %d", GetLastError());
1080         JLI_MemFree(*cmd_line_utf8);
1081         return JNI_FALSE;
1082     }
1083     return JNI_TRUE;
1084 }
1085 
1086 /*
1087  * Translate command line arguments from Windows format to argc+argv.
1088  */
1089 static void
1090 ConvertWinArgsToCommonFormat(LPSTR cmd_line, int *pargc, char*** pargv) {
1091     JLI_CmdToArgs(cmd_line);
1092 
1093     *pargc = JLI_GetStdArgc();
1094     // add one more to mark the end
1095     *pargv = (char **)JLI_MemAlloc((*pargc + 1) * (sizeof(char *)));
1096     {
1097         int i = 0;
1098         StdArg *stdargs = JLI_GetStdArgs();
1099         for (i = 0 ; i < *pargc ; ++i) {
1100             (*pargv)[i] = stdargs[i].arg;
1101         }
1102         (*pargv)[i] = NULL;
1103     }
1104 }
1105 
1106 jboolean
1107 JLI_DecodeArgs(int *pargc, char*** pargv) {
1108     LPSTR cmdLineUtf8;
1109 
1110     // On Windows command line arguments could be encoded as Unicode
1111     // if it is declared explicitly.
1112     // Try to parse them as Unicode and look for Unicode encoding request
1113     if (!DecodeUnicodeArgs(GetCommandLineW(), &cmdLineUtf8)) {
1114         return JNI_FALSE;
1115     }
1116     ConvertWinArgsToCommonFormat(cmdLineUtf8, pargc, pargv);
1117     JLI_MemFree(cmdLineUtf8);
1118 
1119     // If arguments are not on Unicode, decode them as chars.
1120     if (!IsArgsUnicodeDecodingRequired(*pargc, *pargv)) {
1121         JLI_MemFree(*pargv);
1122         JLI_ReleaseStdArgs();
1123         ConvertWinArgsToCommonFormat(GetCommandLine(), pargc, pargv);
1124     }
1125     return JNI_TRUE;
1126 }