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