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