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