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