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