1 /*
   2  * Copyright (c) 1997, 2013, 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 #include "version_comp.h"
  41 
  42 #define JVM_DLL "jvm.dll"
  43 #define JAVA_DLL "java.dll"
  44 
  45 /*
  46  * Prototypes.
  47  */
  48 static jboolean GetPublicJREHome(char *path, jint pathsize);
  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 /* We supports warmup for UI stack that is performed in parallel
  54  * to VM initialization.
  55  * This helps to improve startup of UI application as warmup phase
  56  * might be long due to initialization of OS or hardware resources.
  57  * It is not CPU bound and therefore it does not interfere with VM init.
  58  * Obviously such warmup only has sense for UI apps and therefore it needs
  59  * to be explicitly requested by passing -Dsun.awt.warmup=true property
  60  * (this is always the case for plugin/javaws).
  61  *
  62  * Implementation launches new thread after VM starts and use it to perform
  63  * warmup code (platform dependent).
  64  * This thread is later reused as AWT toolkit thread as graphics toolkit
  65  * often assume that they are used from the same thread they were launched on.
  66  *
  67  * At the moment we only support warmup for D3D. It only possible on windows
  68  * and only if other flags do not prohibit this (e.g. OpenGL support requested).
  69  */
  70 #undef ENABLE_AWT_PRELOAD
  71 #ifndef JAVA_ARGS /* turn off AWT preloading for javac, jar, etc */
  72     /* CR6999872: fastdebug crashes if awt library is loaded before JVM is
  73      * initialized*/
  74     #if !defined(DEBUG)
  75         #define ENABLE_AWT_PRELOAD
  76     #endif
  77 #endif
  78 
  79 #ifdef ENABLE_AWT_PRELOAD
  80 /* "AWT was preloaded" flag;
  81  * turned on by AWTPreload().
  82  */
  83 int awtPreloaded = 0;
  84 
  85 /* Calls a function with the name specified
  86  * the function must be int(*fn)(void).
  87  */
  88 int AWTPreload(const char *funcName);
  89 /* stops AWT preloading */
  90 void AWTPreloadStop();
  91 
  92 /* D3D preloading */
  93 /* -1: not initialized; 0: OFF, 1: ON */
  94 int awtPreloadD3D = -1;
  95 /* command line parameter to swith D3D preloading on */
  96 #define PARAM_PRELOAD_D3D "-Dsun.awt.warmup"
  97 /* D3D/OpenGL management parameters */
  98 #define PARAM_NODDRAW "-Dsun.java2d.noddraw"
  99 #define PARAM_D3D "-Dsun.java2d.d3d"
 100 #define PARAM_OPENGL "-Dsun.java2d.opengl"
 101 /* funtion in awt.dll (src/windows/native/sun/java2d/d3d/D3DPipelineManager.cpp) */
 102 #define D3D_PRELOAD_FUNC "preloadD3D"
 103 
 104 /* Extracts value of a parameter with the specified name
 105  * from command line argument (returns pointer in the argument).
 106  * Returns NULL if the argument does not contains the parameter.
 107  * e.g.:
 108  * GetParamValue("theParam", "theParam=value") returns pointer to "value".
 109  */
 110 const char * GetParamValue(const char *paramName, const char *arg) {
 111     int nameLen = JLI_StrLen(paramName);
 112     if (JLI_StrNCmp(paramName, arg, nameLen) == 0) {
 113         /* arg[nameLen] is valid (may contain final NULL) */
 114         if (arg[nameLen] == '=') {
 115             return arg + nameLen + 1;
 116         }
 117     }
 118     return NULL;
 119 }
 120 
 121 /* Checks if commandline argument contains property specified
 122  * and analyze it as boolean property (true/false).
 123  * Returns -1 if the argument does not contain the parameter;
 124  * Returns 1 if the argument contains the parameter and its value is "true";
 125  * Returns 0 if the argument contains the parameter and its value is "false".
 126  */
 127 int GetBoolParamValue(const char *paramName, const char *arg) {
 128     const char * paramValue = GetParamValue(paramName, arg);
 129     if (paramValue != NULL) {
 130         if (JLI_StrCaseCmp(paramValue, "true") == 0) {
 131             return 1;
 132         }
 133         if (JLI_StrCaseCmp(paramValue, "false") == 0) {
 134             return 0;
 135         }
 136     }
 137     return -1;
 138 }
 139 #endif /* ENABLE_AWT_PRELOAD */
 140 
 141 
 142 static jboolean _isjavaw = JNI_FALSE;
 143 
 144 
 145 jboolean
 146 IsJavaw()
 147 {
 148     return _isjavaw;
 149 }
 150 
 151 /*
 152  * Returns the arch path, to get the current arch use the
 153  * macro GetArch, nbits here is ignored for now.
 154  */
 155 const char *
 156 GetArchPath(int nbits)
 157 {
 158 #ifdef _M_AMD64
 159     return "amd64";
 160 #elif defined(_M_IA64)
 161     return "ia64";
 162 #else
 163     return "i386";
 164 #endif
 165 }
 166 
 167 /*
 168  *
 169  */
 170 void
 171 CreateExecutionEnvironment(int *pargc, char ***pargv,
 172                            char *jrepath, jint so_jrepath,
 173                            char *jvmpath, jint so_jvmpath,
 174                            char *jvmcfg,  jint so_jvmcfg) {
 175     char * jvmtype;
 176     int i = 0;
 177     int running = CURRENT_DATA_MODEL;
 178 
 179     int wanted = running;
 180 
 181     char** argv = *pargv;
 182     for (i = 1; i < *pargc ; i++) {
 183         if (JLI_StrCmp(argv[i], "-J-d64") == 0 || JLI_StrCmp(argv[i], "-d64") == 0) {
 184             wanted = 64;
 185             continue;
 186         }
 187         if (JLI_StrCmp(argv[i], "-J-d32") == 0 || JLI_StrCmp(argv[i], "-d32") == 0) {
 188             wanted = 32;
 189             continue;
 190         }
 191 
 192         if (IsJavaArgs() && argv[i][0] != '-')
 193             continue;
 194         if (argv[i][0] != '-')
 195             break;
 196     }
 197     if (running != wanted) {
 198         JLI_ReportErrorMessage(JRE_ERROR2, wanted);
 199         exit(1);
 200     }
 201 
 202     /* Find out where the JRE is that we will be using. */
 203     if (!GetJREPath(jrepath, so_jrepath)) {
 204         JLI_ReportErrorMessage(JRE_ERROR1);
 205         exit(2);
 206     }
 207 
 208     JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%s%s%sjvm.cfg",
 209         jrepath, FILESEP, FILESEP, (char*)GetArch(), FILESEP);
 210 
 211     /* Find the specified JVM type */
 212     if (ReadKnownVMs(jvmcfg, JNI_FALSE) < 1) {
 213         JLI_ReportErrorMessage(CFG_ERROR7);
 214         exit(1);
 215     }
 216 
 217     jvmtype = CheckJvmType(pargc, pargv, JNI_FALSE);
 218     if (JLI_StrCmp(jvmtype, "ERROR") == 0) {
 219         JLI_ReportErrorMessage(CFG_ERROR9);
 220         exit(4);
 221     }
 222 
 223     jvmpath[0] = '\0';
 224     if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath)) {
 225         JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath);
 226         exit(4);
 227     }
 228     /* If we got here, jvmpath has been correctly initialized. */
 229 
 230     /* Check if we need preload AWT */
 231 #ifdef ENABLE_AWT_PRELOAD
 232     argv = *pargv;
 233     for (i = 0; i < *pargc ; i++) {
 234         /* Tests the "turn on" parameter only if not set yet. */
 235         if (awtPreloadD3D < 0) {
 236             if (GetBoolParamValue(PARAM_PRELOAD_D3D, argv[i]) == 1) {
 237                 awtPreloadD3D = 1;
 238             }
 239         }
 240         /* Test parameters which can disable preloading if not already disabled. */
 241         if (awtPreloadD3D != 0) {
 242             if (GetBoolParamValue(PARAM_NODDRAW, argv[i]) == 1
 243                 || GetBoolParamValue(PARAM_D3D, argv[i]) == 0
 244                 || GetBoolParamValue(PARAM_OPENGL, argv[i]) == 1)
 245             {
 246                 awtPreloadD3D = 0;
 247                 /* no need to test the rest of the parameters */
 248                 break;
 249             }
 250         }
 251     }
 252 #endif /* ENABLE_AWT_PRELOAD */
 253 }
 254 
 255 
 256 static jboolean
 257 LoadMSVCRT()
 258 {
 259     // Only do this once
 260     static int loaded = 0;
 261     char crtpath[MAXPATHLEN];
 262 
 263     if (!loaded) {
 264         /*
 265          * The Microsoft C Runtime Library needs to be loaded first.  A copy is
 266          * assumed to be present in the "JRE path" directory.  If it is not found
 267          * there (or "JRE path" fails to resolve), skip the explicit load and let
 268          * nature take its course, which is likely to be a failure to execute.
 269          * This is clearly completely specific to the exact compiler version
 270          * which isn't very nice, but its hardly the only place.
 271          * No attempt to look for compiler versions in between 2003 and 2010
 272          * as we aren't supporting building with those.
 273          */
 274 #ifdef _MSC_VER
 275 #if _MSC_VER < 1400
 276 #define CRT_DLL "msvcr71.dll"
 277 #endif
 278 #if _MSC_VER >= 1600
 279 #define CRT_DLL "msvcr100.dll"
 280 #endif
 281 #ifdef CRT_DLL
 282         if (GetJREPath(crtpath, MAXPATHLEN)) {
 283             if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") +
 284                     JLI_StrLen(CRT_DLL) >= MAXPATHLEN) {
 285                 JLI_ReportErrorMessage(JRE_ERROR11);
 286                 return JNI_FALSE;
 287             }
 288             (void)JLI_StrCat(crtpath, "\\bin\\" CRT_DLL);   /* Add crt dll */
 289             JLI_TraceLauncher("CRT path is %s\n", crtpath);
 290             if (_access(crtpath, 0) == 0) {
 291                 if (LoadLibrary(crtpath) == 0) {
 292                     JLI_ReportErrorMessage(DLL_ERROR4, crtpath);
 293                     return JNI_FALSE;
 294                 }
 295             }
 296         }
 297 #endif /* CRT_DLL */
 298 #endif /* _MSC_VER */
 299         loaded = 1;
 300     }
 301     return JNI_TRUE;
 302 }
 303 
 304 
 305 /*
 306  * Find path to JRE based on .exe's location or registry settings.
 307  */
 308 jboolean
 309 GetJREPath(char *path, jint pathsize)
 310 {
 311     char javadll[MAXPATHLEN];
 312     struct stat s;
 313 
 314     if (GetApplicationHome(path, pathsize)) {
 315         /* Is JRE co-located with the application? */
 316         JLI_Snprintf(javadll, sizeof(javadll), "%s\\bin\\" JAVA_DLL, path);
 317         if (stat(javadll, &s) == 0) {
 318             JLI_TraceLauncher("JRE path is %s\n", path);
 319             return JNI_TRUE;
 320         }
 321 
 322         /* Does this app ship a private JRE in <apphome>\jre directory? */
 323         JLI_Snprintf(javadll, sizeof (javadll), "%s\\jre\\bin\\" JAVA_DLL, path);
 324         if (stat(javadll, &s) == 0) {
 325             JLI_StrCat(path, "\\jre");
 326             JLI_TraceLauncher("JRE path is %s\n", path);
 327             return JNI_TRUE;
 328         }
 329     }
 330 
 331     /* Look for a public JRE on this machine. */
 332     if (GetPublicJREHome(path, pathsize)) {
 333         JLI_TraceLauncher("JRE path is %s\n", path);
 334         return JNI_TRUE;
 335     }
 336 
 337     JLI_ReportErrorMessage(JRE_ERROR8 JAVA_DLL);
 338     return JNI_FALSE;
 339 
 340 }
 341 
 342 /*
 343  * Given a JRE location and a JVM type, construct what the name the
 344  * JVM shared library will be.  Return true, if such a library
 345  * exists, false otherwise.
 346  */
 347 static jboolean
 348 GetJVMPath(const char *jrepath, const char *jvmtype,
 349            char *jvmpath, jint jvmpathsize)
 350 {
 351     struct stat s;
 352     if (JLI_StrChr(jvmtype, '/') || JLI_StrChr(jvmtype, '\\')) {
 353         JLI_Snprintf(jvmpath, jvmpathsize, "%s\\" JVM_DLL, jvmtype);
 354     } else {
 355         JLI_Snprintf(jvmpath, jvmpathsize, "%s\\bin\\%s\\" JVM_DLL,
 356                      jrepath, jvmtype);
 357     }
 358     if (stat(jvmpath, &s) == 0) {
 359         return JNI_TRUE;
 360     } else {
 361         return JNI_FALSE;
 362     }
 363 }
 364 
 365 /*
 366  * Load a jvm from "jvmpath" and initialize the invocation functions.
 367  */
 368 jboolean
 369 LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)
 370 {
 371     HINSTANCE handle;
 372 
 373     JLI_TraceLauncher("JVM path is %s\n", jvmpath);
 374 
 375     /*
 376      * The Microsoft C Runtime Library needs to be loaded first.  A copy is
 377      * assumed to be present in the "JRE path" directory.  If it is not found
 378      * there (or "JRE path" fails to resolve), skip the explicit load and let
 379      * nature take its course, which is likely to be a failure to execute.
 380      *
 381      */
 382     LoadMSVCRT();
 383 
 384     /* Load the Java VM DLL */
 385     if ((handle = LoadLibrary(jvmpath)) == 0) {
 386         JLI_ReportErrorMessage(DLL_ERROR4, (char *)jvmpath);
 387         return JNI_FALSE;
 388     }
 389 
 390     /* Now get the function addresses */
 391     ifn->CreateJavaVM =
 392         (void *)GetProcAddress(handle, "JNI_CreateJavaVM");
 393     ifn->GetDefaultJavaVMInitArgs =
 394         (void *)GetProcAddress(handle, "JNI_GetDefaultJavaVMInitArgs");
 395     if (ifn->CreateJavaVM == 0 || ifn->GetDefaultJavaVMInitArgs == 0) {
 396         JLI_ReportErrorMessage(JNI_ERROR1, (char *)jvmpath);
 397         return JNI_FALSE;
 398     }
 399 
 400     return JNI_TRUE;
 401 }
 402 
 403 /*
 404  * If app is "c:\foo\bin\javac", then put "c:\foo" into buf.
 405  */
 406 jboolean
 407 GetApplicationHome(char *buf, jint bufsize)
 408 {
 409     char *cp;
 410     GetModuleFileName(0, buf, bufsize);
 411     *JLI_StrRChr(buf, '\\') = '\0'; /* remove .exe file name */
 412     if ((cp = JLI_StrRChr(buf, '\\')) == 0) {
 413         /* This happens if the application is in a drive root, and
 414          * there is no bin directory. */
 415         buf[0] = '\0';
 416         return JNI_FALSE;
 417     }
 418     *cp = '\0';  /* remove the bin\ part */
 419     return JNI_TRUE;
 420 }
 421 
 422 /*
 423  * Helpers to look in the registry for a public JRE.
 424  */
 425                     /* Same for 1.5.0, 1.5.1, 1.5.2 etc. */
 426 #define JRE_KEY     "Software\\JavaSoft\\Java Runtime Environment"
 427 
 428 static jboolean
 429 GetStringFromRegistry(HKEY key, const char *name, char *buf, jint bufsize)
 430 {
 431     DWORD type, size;
 432 
 433     if (RegQueryValueEx(key, name, 0, &type, 0, &size) == 0
 434         && type == REG_SZ
 435         && (size < (unsigned int)bufsize)) {
 436         if (RegQueryValueEx(key, name, 0, 0, buf, &size) == 0) {
 437             return JNI_TRUE;
 438         }
 439     }
 440     return JNI_FALSE;
 441 }
 442 
 443 static jboolean
 444 GetPublicJREHome(char *buf, jint bufsize)
 445 {
 446     HKEY key, subkey;
 447     char version[MAXPATHLEN];
 448 
 449     /*
 450      * Note: There is a very similar implementation of the following
 451      * registry reading code in the Windows java control panel (javacp.cpl).
 452      * If there are bugs here, a similar bug probably exists there.  Hence,
 453      * changes here require inspection there.
 454      */
 455 
 456     /* Find the current version of the JRE */
 457     if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, JRE_KEY, 0, KEY_READ, &key) != 0) {
 458         JLI_ReportErrorMessage(REG_ERROR1, JRE_KEY);
 459         return JNI_FALSE;
 460     }
 461 
 462     if (!GetStringFromRegistry(key, "CurrentVersion",
 463                                version, sizeof(version))) {
 464         JLI_ReportErrorMessage(REG_ERROR2, JRE_KEY);
 465         RegCloseKey(key);
 466         return JNI_FALSE;
 467     }
 468 
 469     if (JLI_StrCmp(version, GetDotVersion()) != 0) {
 470         JLI_ReportErrorMessage(REG_ERROR3, JRE_KEY, version, GetDotVersion()
 471         );
 472         RegCloseKey(key);
 473         return JNI_FALSE;
 474     }
 475 
 476     /* Find directory where the current version is installed. */
 477     if (RegOpenKeyEx(key, version, 0, KEY_READ, &subkey) != 0) {
 478         JLI_ReportErrorMessage(REG_ERROR1, JRE_KEY, version);
 479         RegCloseKey(key);
 480         return JNI_FALSE;
 481     }
 482 
 483     if (!GetStringFromRegistry(subkey, "JavaHome", buf, bufsize)) {
 484         JLI_ReportErrorMessage(REG_ERROR4, JRE_KEY, version);
 485         RegCloseKey(key);
 486         RegCloseKey(subkey);
 487         return JNI_FALSE;
 488     }
 489 
 490     if (JLI_IsTraceLauncher()) {
 491         char micro[MAXPATHLEN];
 492         if (!GetStringFromRegistry(subkey, "MicroVersion", micro,
 493                                    sizeof(micro))) {
 494             printf("Warning: Can't read MicroVersion\n");
 495             micro[0] = '\0';
 496         }
 497         printf("Version major.minor.micro = %s.%s\n", version, micro);
 498     }
 499 
 500     RegCloseKey(key);
 501     RegCloseKey(subkey);
 502     return JNI_TRUE;
 503 }
 504 
 505 /*
 506  * Support for doing cheap, accurate interval timing.
 507  */
 508 static jboolean counterAvailable = JNI_FALSE;
 509 static jboolean counterInitialized = JNI_FALSE;
 510 static LARGE_INTEGER counterFrequency;
 511 
 512 jlong CounterGet()
 513 {
 514     LARGE_INTEGER count;
 515 
 516     if (!counterInitialized) {
 517         counterAvailable = QueryPerformanceFrequency(&counterFrequency);
 518         counterInitialized = JNI_TRUE;
 519     }
 520     if (!counterAvailable) {
 521         return 0;
 522     }
 523     QueryPerformanceCounter(&count);
 524     return (jlong)(count.QuadPart);
 525 }
 526 
 527 jlong Counter2Micros(jlong counts)
 528 {
 529     if (!counterAvailable || !counterInitialized) {
 530         return 0;
 531     }
 532     return (counts * 1000 * 1000)/counterFrequency.QuadPart;
 533 }
 534 /*
 535  * windows snprintf does not guarantee a null terminator in the buffer,
 536  * if the computed size is equal to or greater than the buffer size,
 537  * as well as error conditions. This function guarantees a null terminator
 538  * under all these conditions. An unreasonable buffer or size will return
 539  * an error value. Under all other conditions this function will return the
 540  * size of the bytes actually written minus the null terminator, similar
 541  * to ansi snprintf api. Thus when calling this function the caller must
 542  * ensure storage for the null terminator.
 543  */
 544 int
 545 JLI_Snprintf(char* buffer, size_t size, const char* format, ...) {
 546     int rc;
 547     va_list vl;
 548     if (size == 0 || buffer == NULL)
 549         return -1;
 550     buffer[0] = '\0';
 551     va_start(vl, format);
 552     rc = vsnprintf(buffer, size, format, vl);
 553     va_end(vl);
 554     /* force a null terminator, if something is amiss */
 555     if (rc < 0) {
 556         /* apply ansi semantics */
 557         buffer[size - 1] = '\0';
 558         return size;
 559     } else if (rc == size) {
 560         /* force a null terminator */
 561         buffer[size - 1] = '\0';
 562     }
 563     return rc;
 564 }
 565 
 566 void
 567 JLI_ReportErrorMessage(const char* fmt, ...) {
 568     va_list vl;
 569     va_start(vl,fmt);
 570 
 571     if (IsJavaw()) {
 572         char *message;
 573 
 574         /* get the length of the string we need */
 575         int n = _vscprintf(fmt, vl);
 576 
 577         message = (char *)JLI_MemAlloc(n + 1);
 578         _vsnprintf(message, n, fmt, vl);
 579         message[n]='\0';
 580         MessageBox(NULL, message, "Java Virtual Machine Launcher",
 581             (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
 582         JLI_MemFree(message);
 583     } else {
 584         vfprintf(stderr, fmt, vl);
 585         fprintf(stderr, "\n");
 586     }
 587     va_end(vl);
 588 }
 589 
 590 /*
 591  * Just like JLI_ReportErrorMessage, except that it concatenates the system
 592  * error message if any, its upto the calling routine to correctly
 593  * format the separation of the messages.
 594  */
 595 void
 596 JLI_ReportErrorMessageSys(const char *fmt, ...)
 597 {
 598     va_list vl;
 599 
 600     int save_errno = errno;
 601     DWORD       errval;
 602     jboolean freeit = JNI_FALSE;
 603     char  *errtext = NULL;
 604 
 605     va_start(vl, fmt);
 606 
 607     if ((errval = GetLastError()) != 0) {               /* Platform SDK / DOS Error */
 608         int n = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|
 609             FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_ALLOCATE_BUFFER,
 610             NULL, errval, 0, (LPTSTR)&errtext, 0, NULL);
 611         if (errtext == NULL || n == 0) {                /* Paranoia check */
 612             errtext = "";
 613             n = 0;
 614         } else {
 615             freeit = JNI_TRUE;
 616             if (n > 2) {                                /* Drop final CR, LF */
 617                 if (errtext[n - 1] == '\n') n--;
 618                 if (errtext[n - 1] == '\r') n--;
 619                 errtext[n] = '\0';
 620             }
 621         }
 622     } else {   /* C runtime error that has no corresponding DOS error code */
 623         errtext = strerror(save_errno);
 624     }
 625 
 626     if (IsJavaw()) {
 627         char *message;
 628         int mlen;
 629         /* get the length of the string we need */
 630         int len = mlen =  _vscprintf(fmt, vl) + 1;
 631         if (freeit) {
 632            mlen += (int)JLI_StrLen(errtext);
 633         }
 634 
 635         message = (char *)JLI_MemAlloc(mlen);
 636         _vsnprintf(message, len, fmt, vl);
 637         message[len]='\0';
 638 
 639         if (freeit) {
 640            JLI_StrCat(message, errtext);
 641         }
 642 
 643         MessageBox(NULL, message, "Java Virtual Machine Launcher",
 644             (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
 645 
 646         JLI_MemFree(message);
 647     } else {
 648         vfprintf(stderr, fmt, vl);
 649         if (freeit) {
 650            fprintf(stderr, "%s", errtext);
 651         }
 652     }
 653     if (freeit) {
 654         (void)LocalFree((HLOCAL)errtext);
 655     }
 656     va_end(vl);
 657 }
 658 
 659 void  JLI_ReportExceptionDescription(JNIEnv * env) {
 660     if (IsJavaw()) {
 661        /*
 662         * This code should be replaced by code which opens a window with
 663         * the exception detail message, for now atleast put a dialog up.
 664         */
 665         MessageBox(NULL, "A Java Exception has occurred.", "Java Virtual Machine Launcher",
 666                (MB_OK|MB_ICONSTOP|MB_APPLMODAL));
 667     } else {
 668         (*env)->ExceptionDescribe(env);
 669     }
 670 }
 671 
 672 jboolean
 673 ServerClassMachine() {
 674     return (GetErgoPolicy() == ALWAYS_SERVER_CLASS) ? JNI_TRUE : JNI_FALSE;
 675 }
 676 
 677 /*
 678  * Determine if there is an acceptable JRE in the registry directory top_key.
 679  * Upon locating the "best" one, return a fully qualified path to it.
 680  * "Best" is defined as the most advanced JRE meeting the constraints
 681  * contained in the manifest_info. If no JRE in this directory meets the
 682  * constraints, return NULL.
 683  *
 684  * It doesn't matter if we get an error reading the registry, or we just
 685  * don't find anything interesting in the directory.  We just return NULL
 686  * in either case.
 687  */
 688 static char *
 689 ProcessDir(manifest_info* info, HKEY top_key) {
 690     DWORD   index = 0;
 691     HKEY    ver_key;
 692     char    name[MAXNAMELEN];
 693     int     len;
 694     char    *best = NULL;
 695 
 696     /*
 697      * Enumerate "<top_key>/SOFTWARE/JavaSoft/Java Runtime Environment"
 698      * searching for the best available version.
 699      */
 700     while (RegEnumKey(top_key, index, name, MAXNAMELEN) == ERROR_SUCCESS) {
 701         index++;
 702         if (JLI_AcceptableRelease(name, info->jre_version))
 703             if ((best == NULL) || (JLI_ExactVersionId(name, best) > 0)) {
 704                 if (best != NULL)
 705                     JLI_MemFree(best);
 706                 best = JLI_StringDup(name);
 707             }
 708     }
 709 
 710     /*
 711      * Extract "JavaHome" from the "best" registry directory and return
 712      * that path.  If no appropriate version was located, or there is an
 713      * error in extracting the "JavaHome" string, return null.
 714      */
 715     if (best == NULL)
 716         return (NULL);
 717     else {
 718         if (RegOpenKeyEx(top_key, best, 0, KEY_READ, &ver_key)
 719           != ERROR_SUCCESS) {
 720             JLI_MemFree(best);
 721             if (ver_key != NULL)
 722                 RegCloseKey(ver_key);
 723             return (NULL);
 724         }
 725         JLI_MemFree(best);
 726         len = MAXNAMELEN;
 727         if (RegQueryValueEx(ver_key, "JavaHome", NULL, NULL, (LPBYTE)name, &len)
 728           != ERROR_SUCCESS) {
 729             if (ver_key != NULL)
 730                 RegCloseKey(ver_key);
 731             return (NULL);
 732         }
 733         if (ver_key != NULL)
 734             RegCloseKey(ver_key);
 735         return (JLI_StringDup(name));
 736     }
 737 }
 738 
 739 /*
 740  * This is the global entry point. It examines the host for the optimal
 741  * JRE to be used by scanning a set of registry entries.  This set of entries
 742  * is hardwired on Windows as "Software\JavaSoft\Java Runtime Environment"
 743  * under the set of roots "{ HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }".
 744  *
 745  * This routine simply opens each of these registry directories before passing
 746  * control onto ProcessDir().
 747  */
 748 char *
 749 LocateJRE(manifest_info* info) {
 750     HKEY    key = NULL;
 751     char    *path;
 752     int     key_index;
 753     HKEY    root_keys[2] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE };
 754 
 755     for (key_index = 0; key_index <= 1; key_index++) {
 756         if (RegOpenKeyEx(root_keys[key_index], JRE_KEY, 0, KEY_READ, &key)
 757           == ERROR_SUCCESS)
 758             if ((path = ProcessDir(info, key)) != NULL) {
 759                 if (key != NULL)
 760                     RegCloseKey(key);
 761                 return (path);
 762             }
 763         if (key != NULL)
 764             RegCloseKey(key);
 765     }
 766     return NULL;
 767 }
 768 
 769 /*
 770  * Local helper routine to isolate a single token (option or argument)
 771  * from the command line.
 772  *
 773  * This routine accepts a pointer to a character pointer.  The first
 774  * token (as defined by MSDN command-line argument syntax) is isolated
 775  * from that string.
 776  *
 777  * Upon return, the input character pointer pointed to by the parameter s
 778  * is updated to point to the remainding, unscanned, portion of the string,
 779  * or to a null character if the entire string has been consummed.
 780  *
 781  * This function returns a pointer to a null-terminated string which
 782  * contains the isolated first token, or to the null character if no
 783  * token could be isolated.
 784  *
 785  * Note the side effect of modifying the input string s by the insertion
 786  * of a null character, making it two strings.
 787  *
 788  * See "Parsing C Command-Line Arguments" in the MSDN Library for the
 789  * parsing rule details.  The rule summary from that specification is:
 790  *
 791  *  * Arguments are delimited by white space, which is either a space or a tab.
 792  *
 793  *  * A string surrounded by double quotation marks is interpreted as a single
 794  *    argument, regardless of white space contained within. A quoted string can
 795  *    be embedded in an argument. Note that the caret (^) is not recognized as
 796  *    an escape character or delimiter.
 797  *
 798  *  * A double quotation mark preceded by a backslash, \", is interpreted as a
 799  *    literal double quotation mark (").
 800  *
 801  *  * Backslashes are interpreted literally, unless they immediately precede a
 802  *    double quotation mark.
 803  *
 804  *  * If an even number of backslashes is followed by a double quotation mark,
 805  *    then one backslash (\) is placed in the argv array for every pair of
 806  *    backslashes (\\), and the double quotation mark (") is interpreted as a
 807  *    string delimiter.
 808  *
 809  *  * If an odd number of backslashes is followed by a double quotation mark,
 810  *    then one backslash (\) is placed in the argv array for every pair of
 811  *    backslashes (\\) and the double quotation mark is interpreted as an
 812  *    escape sequence by the remaining backslash, causing a literal double
 813  *    quotation mark (") to be placed in argv.
 814  */
 815 static char*
 816 nextarg(char** s) {
 817     char    *p = *s;
 818     char    *head;
 819     int     slashes = 0;
 820     int     inquote = 0;
 821 
 822     /*
 823      * Strip leading whitespace, which MSDN defines as only space or tab.
 824      * (Hence, no locale specific "isspace" here.)
 825      */
 826     while (*p != (char)0 && (*p == ' ' || *p == '\t'))
 827         p++;
 828     head = p;                   /* Save the start of the token to return */
 829 
 830     /*
 831      * Isolate a token from the command line.
 832      */
 833     while (*p != (char)0 && (inquote || !(*p == ' ' || *p == '\t'))) {
 834         if (*p == '\\' && *(p+1) == '"' && slashes % 2 == 0)
 835             p++;
 836         else if (*p == '"')
 837             inquote = !inquote;
 838         slashes = (*p++ == '\\') ? slashes + 1 : 0;
 839     }
 840 
 841     /*
 842      * If the token isolated isn't already terminated in a "char zero",
 843      * then replace the whitespace character with one and move to the
 844      * next character.
 845      */
 846     if (*p != (char)0)
 847         *p++ = (char)0;
 848 
 849     /*
 850      * Update the parameter to point to the head of the remaining string
 851      * reflecting the command line and return a pointer to the leading
 852      * token which was isolated from the command line.
 853      */
 854     *s = p;
 855     return (head);
 856 }
 857 
 858 /*
 859  * Local helper routine to return a string equivalent to the input string
 860  * s, but with quotes removed so the result is a string as would be found
 861  * in argv[].  The returned string should be freed by a call to JLI_MemFree().
 862  *
 863  * The rules for quoting (and escaped quotes) are:
 864  *
 865  *  1 A double quotation mark preceded by a backslash, \", is interpreted as a
 866  *    literal double quotation mark (").
 867  *
 868  *  2 Backslashes are interpreted literally, unless they immediately precede a
 869  *    double quotation mark.
 870  *
 871  *  3 If an even number of backslashes is followed by a double quotation mark,
 872  *    then one backslash (\) is placed in the argv array for every pair of
 873  *    backslashes (\\), and the double quotation mark (") is interpreted as a
 874  *    string delimiter.
 875  *
 876  *  4 If an odd number of backslashes is followed by a double quotation mark,
 877  *    then one backslash (\) is placed in the argv array for every pair of
 878  *    backslashes (\\) and the double quotation mark is interpreted as an
 879  *    escape sequence by the remaining backslash, causing a literal double
 880  *    quotation mark (") to be placed in argv.
 881  */
 882 static char*
 883 unquote(const char *s) {
 884     const char *p = s;          /* Pointer to the tail of the original string */
 885     char *un = (char*)JLI_MemAlloc(JLI_StrLen(s) + 1);  /* Ptr to unquoted string */
 886     char *pun = un;             /* Pointer to the tail of the unquoted string */
 887 
 888     while (*p != '\0') {
 889         if (*p == '"') {
 890             p++;
 891         } else if (*p == '\\') {
 892             const char *q = p + JLI_StrSpn(p,"\\");
 893             if (*q == '"')
 894                 do {
 895                     *pun++ = '\\';
 896                     p += 2;
 897                  } while (*p == '\\' && p < q);
 898             else
 899                 while (p < q)
 900                     *pun++ = *p++;
 901         } else {
 902             *pun++ = *p++;
 903         }
 904     }
 905     *pun = '\0';
 906     return un;
 907 }
 908 
 909 /*
 910  * Given a path to a jre to execute, this routine checks if this process
 911  * is indeed that jre.  If not, it exec's that jre.
 912  *
 913  * We want to actually check the paths rather than just the version string
 914  * built into the executable, so that given version specification will yield
 915  * the exact same Java environment, regardless of the version of the arbitrary
 916  * launcher we start with.
 917  */
 918 void
 919 ExecJRE(char *jre, char **argv) {
 920     jint     len;
 921     char    path[MAXPATHLEN + 1];
 922 
 923     const char *progname = GetProgramName();
 924 
 925     /*
 926      * Resolve the real path to the currently running launcher.
 927      */
 928     len = GetModuleFileName(NULL, path, MAXPATHLEN + 1);
 929     if (len == 0 || len > MAXPATHLEN) {
 930         JLI_ReportErrorMessageSys(JRE_ERROR9, progname);
 931         exit(1);
 932     }
 933 
 934     JLI_TraceLauncher("ExecJRE: old: %s\n", path);
 935     JLI_TraceLauncher("ExecJRE: new: %s\n", jre);
 936 
 937     /*
 938      * If the path to the selected JRE directory is a match to the initial
 939      * portion of the path to the currently executing JRE, we have a winner!
 940      * If so, just return.
 941      */
 942     if (JLI_StrNCaseCmp(jre, path, JLI_StrLen(jre)) == 0)
 943         return;                 /* I am the droid you were looking for */
 944 
 945     /*
 946      * If this isn't the selected version, exec the selected version.
 947      */
 948     JLI_Snprintf(path, sizeof(path), "%s\\bin\\%s.exe", jre, progname);
 949 
 950     /*
 951      * Although Windows has an execv() entrypoint, it doesn't actually
 952      * overlay a process: it can only create a new process and terminate
 953      * the old process.  Therefore, any processes waiting on the initial
 954      * process wake up and they shouldn't.  Hence, a chain of pseudo-zombie
 955      * processes must be retained to maintain the proper wait semantics.
 956      * Fortunately the image size of the launcher isn't too large at this
 957      * time.
 958      *
 959      * If it weren't for this semantic flaw, the code below would be ...
 960      *
 961      *     execv(path, argv);
 962      *     JLI_ReportErrorMessage("Error: Exec of %s failed\n", path);
 963      *     exit(1);
 964      *
 965      * The incorrect exec semantics could be addressed by:
 966      *
 967      *     exit((int)spawnv(_P_WAIT, path, argv));
 968      *
 969      * Unfortunately, a bug in Windows spawn/exec impementation prevents
 970      * this from completely working.  All the Windows POSIX process creation
 971      * interfaces are implemented as wrappers around the native Windows
 972      * function CreateProcess().  CreateProcess() takes a single string
 973      * to specify command line options and arguments, so the POSIX routine
 974      * wrappers build a single string from the argv[] array and in the
 975      * process, any quoting information is lost.
 976      *
 977      * The solution to this to get the original command line, to process it
 978      * to remove the new multiple JRE options (if any) as was done for argv
 979      * in the common SelectVersion() routine and finally to pass it directly
 980      * to the native CreateProcess() Windows process control interface.
 981      */
 982     {
 983         char    *cmdline;
 984         char    *p;
 985         char    *np;
 986         char    *ocl;
 987         char    *ccl;
 988         char    *unquoted;
 989         DWORD   exitCode;
 990         STARTUPINFO si;
 991         PROCESS_INFORMATION pi;
 992 
 993         /*
 994          * The following code block gets and processes the original command
 995          * line, replacing the argv[0] equivalent in the command line with
 996          * the path to the new executable and removing the appropriate
 997          * Multiple JRE support options. Note that similar logic exists
 998          * in the platform independent SelectVersion routine, but is
 999          * replicated here due to the syntax of CreateProcess().
1000          *
1001          * The magic "+ 4" characters added to the command line length are
1002          * 2 possible quotes around the path (argv[0]), a space after the
1003          * path and a terminating null character.
1004          */
1005         ocl = GetCommandLine();
1006         np = ccl = JLI_StringDup(ocl);
1007         p = nextarg(&np);               /* Discard argv[0] */
1008         cmdline = (char *)JLI_MemAlloc(JLI_StrLen(path) + JLI_StrLen(np) + 4);
1009         if (JLI_StrChr(path, (int)' ') == NULL && JLI_StrChr(path, (int)'\t') == NULL)
1010             cmdline = JLI_StrCpy(cmdline, path);
1011         else
1012             cmdline = JLI_StrCat(JLI_StrCat(JLI_StrCpy(cmdline, "\""), path), "\"");
1013 
1014         while (*np != (char)0) {                /* While more command-line */
1015             p = nextarg(&np);
1016             if (*p != (char)0) {                /* If a token was isolated */
1017                 unquoted = unquote(p);
1018                 if (*unquoted == '-') {         /* Looks like an option */
1019                     if (JLI_StrCmp(unquoted, "-classpath") == 0 ||
1020                       JLI_StrCmp(unquoted, "-cp") == 0) {       /* Unique cp syntax */
1021                         cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
1022                         p = nextarg(&np);
1023                         if (*p != (char)0)      /* If a token was isolated */
1024                             cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
1025                     } else if (JLI_StrNCmp(unquoted, "-version:", 9) != 0 &&
1026                       JLI_StrCmp(unquoted, "-jre-restrict-search") != 0 &&
1027                       JLI_StrCmp(unquoted, "-no-jre-restrict-search") != 0) {
1028                         cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
1029                     }
1030                 } else {                        /* End of options */
1031                     cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
1032                     cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), np);
1033                     JLI_MemFree((void *)unquoted);
1034                     break;
1035                 }
1036                 JLI_MemFree((void *)unquoted);
1037             }
1038         }
1039         JLI_MemFree((void *)ccl);
1040 
1041         if (JLI_IsTraceLauncher()) {
1042             np = ccl = JLI_StringDup(cmdline);
1043             p = nextarg(&np);
1044             printf("ReExec Command: %s (%s)\n", path, p);
1045             printf("ReExec Args: %s\n", np);
1046             JLI_MemFree((void *)ccl);
1047         }
1048         (void)fflush(stdout);
1049         (void)fflush(stderr);
1050 
1051         /*
1052          * The following code is modeled after a model presented in the
1053          * Microsoft Technical Article "Moving Unix Applications to
1054          * Windows NT" (March 6, 1994) and "Creating Processes" on MSDN
1055          * (Februrary 2005).  It approximates UNIX spawn semantics with
1056          * the parent waiting for termination of the child.
1057          */
1058         memset(&si, 0, sizeof(si));
1059         si.cb =sizeof(STARTUPINFO);
1060         memset(&pi, 0, sizeof(pi));
1061 
1062         if (!CreateProcess((LPCTSTR)path,       /* executable name */
1063           (LPTSTR)cmdline,                      /* command line */
1064           (LPSECURITY_ATTRIBUTES)NULL,          /* process security attr. */
1065           (LPSECURITY_ATTRIBUTES)NULL,          /* thread security attr. */
1066           (BOOL)TRUE,                           /* inherits system handles */
1067           (DWORD)0,                             /* creation flags */
1068           (LPVOID)NULL,                         /* environment block */
1069           (LPCTSTR)NULL,                        /* current directory */
1070           (LPSTARTUPINFO)&si,                   /* (in) startup information */
1071           (LPPROCESS_INFORMATION)&pi)) {        /* (out) process information */
1072             JLI_ReportErrorMessageSys(SYS_ERROR1, path);
1073             exit(1);
1074         }
1075 
1076         if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_FAILED) {
1077             if (GetExitCodeProcess(pi.hProcess, &exitCode) == FALSE)
1078                 exitCode = 1;
1079         } else {
1080             JLI_ReportErrorMessage(SYS_ERROR2);
1081             exitCode = 1;
1082         }
1083 
1084         CloseHandle(pi.hThread);
1085         CloseHandle(pi.hProcess);
1086 
1087         exit(exitCode);
1088     }
1089 }
1090 
1091 /*
1092  * Wrapper for platform dependent unsetenv function.
1093  */
1094 int
1095 UnsetEnv(char *name)
1096 {
1097     int ret;
1098     char *buf = JLI_MemAlloc(JLI_StrLen(name) + 2);
1099     buf = JLI_StrCat(JLI_StrCpy(buf, name), "=");
1100     ret = _putenv(buf);
1101     JLI_MemFree(buf);
1102     return (ret);
1103 }
1104 
1105 /* --- Splash Screen shared library support --- */
1106 
1107 static const char* SPLASHSCREEN_SO = "\\bin\\splashscreen.dll";
1108 
1109 static HMODULE hSplashLib = NULL;
1110 
1111 void* SplashProcAddress(const char* name) {
1112     char libraryPath[MAXPATHLEN]; /* some extra space for JLI_StrCat'ing SPLASHSCREEN_SO */
1113 
1114     if (!GetJREPath(libraryPath, MAXPATHLEN)) {
1115         return NULL;
1116     }
1117     if (JLI_StrLen(libraryPath)+JLI_StrLen(SPLASHSCREEN_SO) >= MAXPATHLEN) {
1118         return NULL;
1119     }
1120     JLI_StrCat(libraryPath, SPLASHSCREEN_SO);
1121 
1122     if (!hSplashLib) {
1123         hSplashLib = LoadLibrary(libraryPath);
1124     }
1125     if (hSplashLib) {
1126         return GetProcAddress(hSplashLib, name);
1127     } else {
1128         return NULL;
1129     }
1130 }
1131 
1132 void SplashFreeLibrary() {
1133     if (hSplashLib) {
1134         FreeLibrary(hSplashLib);
1135         hSplashLib = NULL;
1136     }
1137 }
1138 
1139 const char *
1140 jlong_format_specifier() {
1141     return "%I64d";
1142 }
1143 
1144 /*
1145  * Block current thread and continue execution in a new thread
1146  */
1147 int
1148 ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void * args) {
1149     int rslt = 0;
1150     unsigned thread_id;
1151 
1152 #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
1153 #define STACK_SIZE_PARAM_IS_A_RESERVATION  (0x10000)
1154 #endif
1155 
1156     /*
1157      * STACK_SIZE_PARAM_IS_A_RESERVATION is what we want, but it's not
1158      * supported on older version of Windows. Try first with the flag; and
1159      * if that fails try again without the flag. See MSDN document or HotSpot
1160      * source (os_win32.cpp) for details.
1161      */
1162     HANDLE thread_handle =
1163       (HANDLE)_beginthreadex(NULL,
1164                              (unsigned)stack_size,
1165                              continuation,
1166                              args,
1167                              STACK_SIZE_PARAM_IS_A_RESERVATION,
1168                              &thread_id);
1169     if (thread_handle == NULL) {
1170       thread_handle =
1171       (HANDLE)_beginthreadex(NULL,
1172                              (unsigned)stack_size,
1173                              continuation,
1174                              args,
1175                              0,
1176                              &thread_id);
1177     }
1178 
1179     /* AWT preloading (AFTER main thread start) */
1180 #ifdef ENABLE_AWT_PRELOAD
1181     /* D3D preloading */
1182     if (awtPreloadD3D != 0) {
1183         char *envValue;
1184         /* D3D routines checks env.var J2D_D3D if no appropriate
1185          * command line params was specified
1186          */
1187         envValue = getenv("J2D_D3D");
1188         if (envValue != NULL && JLI_StrCaseCmp(envValue, "false") == 0) {
1189             awtPreloadD3D = 0;
1190         }
1191         /* Test that AWT preloading isn't disabled by J2D_D3D_PRELOAD env.var */
1192         envValue = getenv("J2D_D3D_PRELOAD");
1193         if (envValue != NULL && JLI_StrCaseCmp(envValue, "false") == 0) {
1194             awtPreloadD3D = 0;
1195         }
1196         if (awtPreloadD3D < 0) {
1197             /* If awtPreloadD3D is still undefined (-1), test
1198              * if it is turned on by J2D_D3D_PRELOAD env.var.
1199              * By default it's turned OFF.
1200              */
1201             awtPreloadD3D = 0;
1202             if (envValue != NULL && JLI_StrCaseCmp(envValue, "true") == 0) {
1203                 awtPreloadD3D = 1;
1204             }
1205          }
1206     }
1207     if (awtPreloadD3D) {
1208         AWTPreload(D3D_PRELOAD_FUNC);
1209     }
1210 #endif /* ENABLE_AWT_PRELOAD */
1211 
1212     if (thread_handle) {
1213       WaitForSingleObject(thread_handle, INFINITE);
1214       GetExitCodeThread(thread_handle, &rslt);
1215       CloseHandle(thread_handle);
1216     } else {
1217       rslt = continuation(args);
1218     }
1219 
1220 #ifdef ENABLE_AWT_PRELOAD
1221     if (awtPreloaded) {
1222         AWTPreloadStop();
1223     }
1224 #endif /* ENABLE_AWT_PRELOAD */
1225 
1226     return rslt;
1227 }
1228 
1229 /* Unix only, empty on windows. */
1230 void SetJavaLauncherPlatformProps() {}
1231 
1232 /*
1233  * The implementation for finding classes from the bootstrap
1234  * class loader, refer to java.h
1235  */
1236 static FindClassFromBootLoader_t *findBootClass = NULL;
1237 
1238 jclass FindBootStrapClass(JNIEnv *env, const char *classname)
1239 {
1240    HMODULE hJvm;
1241 
1242    if (findBootClass == NULL) {
1243        hJvm = GetModuleHandle(JVM_DLL);
1244        if (hJvm == NULL) return NULL;
1245        /* need to use the demangled entry point */
1246        findBootClass = (FindClassFromBootLoader_t *)GetProcAddress(hJvm,
1247             "JVM_FindClassFromBootLoader");
1248        if (findBootClass == NULL) {
1249           JLI_ReportErrorMessage(DLL_ERROR4, "JVM_FindClassFromBootLoader");
1250           return NULL;
1251        }
1252    }
1253    return findBootClass(env, classname);
1254 }
1255 
1256 void
1257 InitLauncher(boolean javaw)
1258 {
1259     INITCOMMONCONTROLSEX icx;
1260 
1261     /*
1262      * Required for javaw mode MessageBox output as well as for
1263      * HotSpot -XX:+ShowMessageBoxOnError in java mode, an empty
1264      * flag field is sufficient to perform the basic UI initialization.
1265      */
1266     memset(&icx, 0, sizeof(INITCOMMONCONTROLSEX));
1267     icx.dwSize = sizeof(INITCOMMONCONTROLSEX);
1268     InitCommonControlsEx(&icx);
1269     _isjavaw = javaw;
1270     JLI_SetTraceLauncher();
1271 }
1272 
1273 
1274 /* ============================== */
1275 /* AWT preloading */
1276 #ifdef ENABLE_AWT_PRELOAD
1277 
1278 typedef int FnPreloadStart(void);
1279 typedef void FnPreloadStop(void);
1280 static FnPreloadStop *fnPreloadStop = NULL;
1281 static HMODULE hPreloadAwt = NULL;
1282 
1283 /*
1284  * Starts AWT preloading
1285  */
1286 int AWTPreload(const char *funcName)
1287 {
1288     int result = -1;
1289     /* load AWT library once (if several preload function should be called) */
1290     if (hPreloadAwt == NULL) {
1291         /* awt.dll is not loaded yet */
1292         char libraryPath[MAXPATHLEN];
1293         int jrePathLen = 0;
1294         HMODULE hJava = NULL;
1295         HMODULE hVerify = NULL;
1296 
1297         while (1) {
1298             /* awt.dll depends on jvm.dll & java.dll;
1299              * jvm.dll is already loaded, so we need only java.dll;
1300              * java.dll depends on MSVCRT lib & verify.dll.
1301              */
1302             if (!GetJREPath(libraryPath, MAXPATHLEN)) {
1303                 break;
1304             }
1305 
1306             /* save path length */
1307             jrePathLen = JLI_StrLen(libraryPath);
1308 
1309             if (jrePathLen + JLI_StrLen("\\bin\\verify.dll") >= MAXPATHLEN) {
1310               /* jre path is too long, the library path will not fit there;
1311                * report and abort preloading
1312                */
1313               JLI_ReportErrorMessage(JRE_ERROR11);
1314               break;
1315             }
1316 
1317             /* load msvcrt 1st */
1318             LoadMSVCRT();
1319 
1320             /* load verify.dll */
1321             JLI_StrCat(libraryPath, "\\bin\\verify.dll");
1322             hVerify = LoadLibrary(libraryPath);
1323             if (hVerify == NULL) {
1324                 break;
1325             }
1326 
1327             /* restore jrePath */
1328             libraryPath[jrePathLen] = 0;
1329             /* load java.dll */
1330             JLI_StrCat(libraryPath, "\\bin\\" JAVA_DLL);
1331             hJava = LoadLibrary(libraryPath);
1332             if (hJava == NULL) {
1333                 break;
1334             }
1335 
1336             /* restore jrePath */
1337             libraryPath[jrePathLen] = 0;
1338             /* load awt.dll */
1339             JLI_StrCat(libraryPath, "\\bin\\awt.dll");
1340             hPreloadAwt = LoadLibrary(libraryPath);
1341             if (hPreloadAwt == NULL) {
1342                 break;
1343             }
1344 
1345             /* get "preloadStop" func ptr */
1346             fnPreloadStop = (FnPreloadStop *)GetProcAddress(hPreloadAwt, "preloadStop");
1347 
1348             break;
1349         }
1350     }
1351 
1352     if (hPreloadAwt != NULL) {
1353         FnPreloadStart *fnInit = (FnPreloadStart *)GetProcAddress(hPreloadAwt, funcName);
1354         if (fnInit != NULL) {
1355             /* don't forget to stop preloading */
1356             awtPreloaded = 1;
1357 
1358             result = fnInit();
1359         }
1360     }
1361 
1362     return result;
1363 }
1364 
1365 /*
1366  * Terminates AWT preloading
1367  */
1368 void AWTPreloadStop() {
1369     if (fnPreloadStop != NULL) {
1370         fnPreloadStop();
1371     }
1372 }
1373 
1374 #endif /* ENABLE_AWT_PRELOAD */
1375 
1376 int
1377 JVMInit(InvocationFunctions* ifn, jlong threadStackSize,
1378         int argc, char **argv,
1379         int mode, char *what, int ret)
1380 {
1381     ShowSplashScreen();
1382     return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret);
1383 }
1384 
1385 void
1386 PostJVMInit(JNIEnv *env, jstring mainClass, JavaVM *vm)
1387 {
1388     // stubbed out for windows and *nixes.
1389 }
1390 
1391 void
1392 RegisterThread()
1393 {
1394     // stubbed out for windows and *nixes.
1395 }
1396 
1397 /*
1398  * on windows, we return a false to indicate this option is not applicable
1399  */
1400 jboolean
1401 ProcessPlatformOption(const char *arg)
1402 {
1403     return JNI_FALSE;
1404 }
1405 
1406 /*
1407  * At this point we have the arguments to the application, and we need to
1408  * check with original stdargs in order to compare which of these truly
1409  * needs expansion. cmdtoargs will specify this if it finds a bare
1410  * (unquoted) argument containing a glob character(s) ie. * or ?
1411  */
1412 jobjectArray
1413 CreateApplicationArgs(JNIEnv *env, char **strv, int argc)
1414 {
1415     int i, j, idx, tlen;
1416     jobjectArray outArray, inArray;
1417     char *ostart, *astart, **nargv;
1418     jboolean needs_expansion = JNI_FALSE;
1419     jmethodID mid;
1420     int stdargc;
1421     StdArg *stdargs;
1422     jclass cls = GetLauncherHelperClass(env);
1423     NULL_CHECK0(cls);
1424 
1425     if (argc == 0) {
1426         return NewPlatformStringArray(env, strv, argc);
1427     }
1428     // the holy grail we need to compare with.
1429     stdargs = JLI_GetStdArgs();
1430     stdargc = JLI_GetStdArgc();
1431 
1432     // sanity check, this should never happen
1433     if (argc > stdargc) {
1434         JLI_TraceLauncher("Warning: app args is larger than the original, %d %d\n", argc, stdargc);
1435         JLI_TraceLauncher("passing arguments as-is.\n");
1436         return NewPlatformStringArray(env, strv, argc);
1437     }
1438 
1439     // sanity check, match the args we have, to the holy grail
1440     idx = stdargc - argc;
1441     ostart = stdargs[idx].arg;
1442     astart = strv[0];
1443     // sanity check, ensure that the first argument of the arrays are the same
1444     if (JLI_StrCmp(ostart, astart) != 0) {
1445         // some thing is amiss the args don't match
1446         JLI_TraceLauncher("Warning: app args parsing error\n");
1447         JLI_TraceLauncher("passing arguments as-is\n");
1448         return NewPlatformStringArray(env, strv, argc);
1449     }
1450 
1451     // make a copy of the args which will be expanded in java if required.
1452     nargv = (char **)JLI_MemAlloc(argc * sizeof(char*));
1453     for (i = 0, j = idx; i < argc; i++, j++) {
1454         jboolean arg_expand = (JLI_StrCmp(stdargs[j].arg, strv[i]) == 0)
1455                                 ? stdargs[j].has_wildcard
1456                                 : JNI_FALSE;
1457         if (needs_expansion == JNI_FALSE)
1458             needs_expansion = arg_expand;
1459 
1460         // indicator char + String + NULL terminator, the java method will strip
1461         // out the first character, the indicator character, so no matter what
1462         // we add the indicator
1463         tlen = 1 + JLI_StrLen(strv[i]) + 1;
1464         nargv[i] = (char *) JLI_MemAlloc(tlen);
1465         if (JLI_Snprintf(nargv[i], tlen, "%c%s", arg_expand ? 'T' : 'F',
1466                          strv[i]) < 0) {
1467             return NULL;
1468         }
1469         JLI_TraceLauncher("%s\n", nargv[i]);
1470     }
1471 
1472     if (!needs_expansion) {
1473         // clean up any allocated memory and return back the old arguments
1474         for (i = 0 ; i < argc ; i++) {
1475             JLI_MemFree(nargv[i]);
1476         }
1477         JLI_MemFree(nargv);
1478         return NewPlatformStringArray(env, strv, argc);
1479     }
1480     NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls,
1481                                                 "expandArgs",
1482                                                 "([Ljava/lang/String;)[Ljava/lang/String;"));
1483 
1484     // expand the arguments that require expansion, the java method will strip
1485     // out the indicator character.
1486     NULL_CHECK0(inArray = NewPlatformStringArray(env, nargv, argc));
1487     outArray = (*env)->CallStaticObjectMethod(env, cls, mid, inArray);
1488     for (i = 0; i < argc; i++) {
1489         JLI_MemFree(nargv[i]);
1490     }
1491     JLI_MemFree(nargv);
1492     return outArray;
1493 }