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