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