1 /* 2 * Copyright (c) 2012, 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 "java.h" 27 #include "jvm_md.h" 28 #include <dirent.h> 29 #include <dlfcn.h> 30 #include <fcntl.h> 31 #include <inttypes.h> 32 #include <stdio.h> 33 #include <string.h> 34 #include <stdlib.h> 35 #include <sys/stat.h> 36 #include <unistd.h> 37 #include <sys/types.h> 38 #include <sys/time.h> 39 40 #include "manifest_info.h" 41 42 /* Support Cocoa event loop on the main thread */ 43 #include <Cocoa/Cocoa.h> 44 #include <objc/objc-runtime.h> 45 #include <objc/objc-auto.h> 46 47 #include <errno.h> 48 #include <spawn.h> 49 50 struct NSAppArgs { 51 int argc; 52 char **argv; 53 }; 54 55 #define JVM_DLL "libjvm.dylib" 56 #define JAVA_DLL "libjava.dylib" 57 /* FALLBACK avoids naming conflicts with system libraries 58 * (eg, ImageIO's libJPEG.dylib) */ 59 #define LD_LIBRARY_PATH "DYLD_FALLBACK_LIBRARY_PATH" 60 61 /* 62 * If a processor / os combination has the ability to run binaries of 63 * two data models and cohabitation of jre/jdk bits with both data 64 * models is supported, then DUAL_MODE is defined. MacOSX is a hybrid 65 * system in that, the universal library can contain all types of libraries 66 * 32/64 and client/server, thus the spawn is capable of linking with the 67 * appropriate library as requested. 68 * 69 * Notes: 70 * 1. VM. DUAL_MODE is disabled, and not supported, however, it is left here in 71 * for experimentation and perhaps enable it in the future. 72 * 2. At the time of this writing, the universal library contains only 73 * a server 64-bit server JVM. 74 * 3. "-client" command line option is supported merely as a command line flag, 75 * for, compatibility reasons, however, a server VM will be launched. 76 */ 77 78 /* 79 * Flowchart of launcher execs and options processing on unix 80 * 81 * The selection of the proper vm shared library to open depends on 82 * several classes of command line options, including vm "flavor" 83 * options (-client, -server) and the data model options, -d32 and 84 * -d64, as well as a version specification which may have come from 85 * the command line or from the manifest of an executable jar file. 86 * The vm selection options are not passed to the running 87 * virtual machine; they must be screened out by the launcher. 88 * 89 * The version specification (if any) is processed first by the 90 * platform independent routine SelectVersion. This may result in 91 * the exec of the specified launcher version. 92 * 93 * Now, in most cases,the launcher will dlopen the target libjvm.so. All 94 * required libraries are loaded by the runtime linker, using the known paths 95 * baked into the shared libraries at compile time. Therefore, 96 * in most cases, the launcher will only exec, if the data models are 97 * mismatched, and will not set any environment variables, regardless of the 98 * data models. 99 * 100 * 101 * 102 * Main 103 * (incoming argv) 104 * | 105 * \|/ 106 * CreateExecutionEnvironment 107 * (determines desired data model) 108 * | 109 * | 110 * \|/ 111 * Have Desired Model ? --> NO --> Is Dual-Mode ? --> NO --> Exit(with error) 112 * | | 113 * | | 114 * | \|/ 115 * | YES 116 * | | 117 * | | 118 * | \|/ 119 * | CheckJvmType 120 * | (removes -client, -server etc.) 121 * | | 122 * | | 123 * \|/ \|/ 124 * YES Find the desired executable/library 125 * | | 126 * | | 127 * \|/ \|/ 128 * CheckJvmType POINT A 129 * (removes -client, -server, etc.) 130 * | 131 * | 132 * \|/ 133 * TranslateDashJArgs... 134 * (Prepare to pass args to vm) 135 * | 136 * | 137 * \|/ 138 * ParseArguments 139 * (removes -d32 and -d64 if any, 140 * processes version options, 141 * creates argument list for vm, 142 * etc.) 143 * | 144 * | 145 * \|/ 146 * POINT A 147 * | 148 * | 149 * \|/ 150 * Path is desired JRE ? YES --> Have Desired Model ? NO --> Re-exec --> Main 151 * NO YES --> Continue 152 * | 153 * | 154 * \|/ 155 * Paths have well known 156 * jvm paths ? --> NO --> Have Desired Model ? NO --> Re-exec --> Main 157 * YES YES --> Continue 158 * | 159 * | 160 * \|/ 161 * Does libjvm.so exist 162 * in any of them ? --> NO --> Have Desired Model ? NO --> Re-exec --> Main 163 * YES YES --> Continue 164 * | 165 * | 166 * \|/ 167 * Re-exec / Spawn 168 * | 169 * | 170 * \|/ 171 * Main 172 */ 173 174 #define GetArch() GetArchPath(CURRENT_DATA_MODEL) 175 176 /* Store the name of the executable once computed */ 177 static char *execname = NULL; 178 179 /* 180 * execname accessor from other parts of platform dependent logic 181 */ 182 const char * 183 GetExecName() { 184 return execname; 185 } 186 187 const char * 188 GetArchPath(int nbits) 189 { 190 switch(nbits) { 191 default: 192 return LIBARCHNAME; 193 } 194 } 195 196 197 /* 198 * Exports the JNI interface from libjli 199 * 200 * This allows client code to link against the .jre/.jdk bundles, 201 * and not worry about trying to pick a HotSpot to link against. 202 * 203 * Switching architectures is unsupported, since client code has 204 * made that choice before the JVM was requested. 205 */ 206 207 static InvocationFunctions *sExportedJNIFunctions = NULL; 208 static char *sPreferredJVMType = NULL; 209 210 static InvocationFunctions *GetExportedJNIFunctions() { 211 if (sExportedJNIFunctions != NULL) return sExportedJNIFunctions; 212 213 char jrePath[PATH_MAX]; 214 jboolean gotJREPath = GetJREPath(jrePath, sizeof(jrePath), GetArch(), JNI_FALSE); 215 if (!gotJREPath) { 216 JLI_ReportErrorMessage("Failed to GetJREPath()"); 217 return NULL; 218 } 219 220 char *preferredJVM = sPreferredJVMType; 221 if (preferredJVM == NULL) { 222 #if defined(__i386__) 223 preferredJVM = "client"; 224 #elif defined(__x86_64__) 225 preferredJVM = "server"; 226 #else 227 #error "Unknown architecture - needs definition" 228 #endif 229 } 230 231 char jvmPath[PATH_MAX]; 232 jboolean gotJVMPath = GetJVMPath(jrePath, preferredJVM, jvmPath, sizeof(jvmPath), GetArch(), CURRENT_DATA_MODEL); 233 if (!gotJVMPath) { 234 JLI_ReportErrorMessage("Failed to GetJVMPath()"); 235 return NULL; 236 } 237 238 InvocationFunctions *fxns = malloc(sizeof(InvocationFunctions)); 239 jboolean vmLoaded = LoadJavaVM(jvmPath, fxns); 240 if (!vmLoaded) { 241 JLI_ReportErrorMessage("Failed to LoadJavaVM()"); 242 return NULL; 243 } 244 245 return sExportedJNIFunctions = fxns; 246 } 247 248 #ifndef STATIC_BUILD 249 250 JNIEXPORT jint JNICALL 251 JNI_GetDefaultJavaVMInitArgs(void *args) { 252 InvocationFunctions *ifn = GetExportedJNIFunctions(); 253 if (ifn == NULL) return JNI_ERR; 254 return ifn->GetDefaultJavaVMInitArgs(args); 255 } 256 257 JNIEXPORT jint JNICALL 258 JNI_CreateJavaVM(JavaVM **pvm, void **penv, void *args) { 259 InvocationFunctions *ifn = GetExportedJNIFunctions(); 260 if (ifn == NULL) return JNI_ERR; 261 return ifn->CreateJavaVM(pvm, penv, args); 262 } 263 264 JNIEXPORT jint JNICALL 265 JNI_GetCreatedJavaVMs(JavaVM **vmBuf, jsize bufLen, jsize *nVMs) { 266 InvocationFunctions *ifn = GetExportedJNIFunctions(); 267 if (ifn == NULL) return JNI_ERR; 268 return ifn->GetCreatedJavaVMs(vmBuf, bufLen, nVMs); 269 } 270 #endif 271 272 /* 273 * Allow JLI-aware launchers to specify a client/server preference 274 */ 275 JNIEXPORT void JNICALL 276 JLI_SetPreferredJVM(const char *prefJVM) { 277 if (sPreferredJVMType != NULL) { 278 free(sPreferredJVMType); 279 sPreferredJVMType = NULL; 280 } 281 282 if (prefJVM == NULL) return; 283 sPreferredJVMType = strdup(prefJVM); 284 } 285 286 static BOOL awtLoaded = NO; 287 static pthread_mutex_t awtLoaded_mutex = PTHREAD_MUTEX_INITIALIZER; 288 static pthread_cond_t awtLoaded_cv = PTHREAD_COND_INITIALIZER; 289 290 JNIEXPORT void JNICALL 291 JLI_NotifyAWTLoaded() 292 { 293 pthread_mutex_lock(&awtLoaded_mutex); 294 awtLoaded = YES; 295 pthread_cond_signal(&awtLoaded_cv); 296 pthread_mutex_unlock(&awtLoaded_mutex); 297 } 298 299 static int (*main_fptr)(int argc, char **argv) = NULL; 300 301 /* 302 * Unwrap the arguments and re-run main() 303 */ 304 static void *apple_main (void *arg) 305 { 306 objc_registerThreadWithCollector(); 307 308 if (main_fptr == NULL) { 309 #ifdef STATIC_BUILD 310 extern int main(int argc, char **argv); 311 main_fptr = &main; 312 #else 313 main_fptr = (int (*)())dlsym(RTLD_DEFAULT, "main"); 314 #endif 315 if (main_fptr == NULL) { 316 JLI_ReportErrorMessageSys("error locating main entrypoint\n"); 317 exit(1); 318 } 319 } 320 321 struct NSAppArgs *args = (struct NSAppArgs *) arg; 322 exit(main_fptr(args->argc, args->argv)); 323 } 324 325 static void dummyTimer(CFRunLoopTimerRef timer, void *info) {} 326 327 static void ParkEventLoop() { 328 // RunLoop needs at least one source, and 1e20 is pretty far into the future 329 CFRunLoopTimerRef t = CFRunLoopTimerCreate(kCFAllocatorDefault, 1.0e20, 0.0, 0, 0, dummyTimer, NULL); 330 CFRunLoopAddTimer(CFRunLoopGetCurrent(), t, kCFRunLoopDefaultMode); 331 CFRelease(t); 332 333 // Park this thread in the main run loop. 334 int32_t result; 335 do { 336 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e20, false); 337 } while (result != kCFRunLoopRunFinished); 338 } 339 340 /* 341 * Mac OS X mandates that the GUI event loop run on very first thread of 342 * an application. This requires that we re-call Java's main() on a new 343 * thread, reserving the 'main' thread for Cocoa. 344 */ 345 static void MacOSXStartup(int argc, char *argv[]) { 346 // Thread already started? 347 static jboolean started = false; 348 if (started) { 349 return; 350 } 351 started = true; 352 353 // Hand off arguments 354 struct NSAppArgs args; 355 args.argc = argc; 356 args.argv = argv; 357 358 // Fire up the main thread 359 pthread_t main_thr; 360 if (pthread_create(&main_thr, NULL, &apple_main, &args) != 0) { 361 JLI_ReportErrorMessageSys("Could not create main thread: %s\n", strerror(errno)); 362 exit(1); 363 } 364 if (pthread_detach(main_thr)) { 365 JLI_ReportErrorMessageSys("pthread_detach() failed: %s\n", strerror(errno)); 366 exit(1); 367 } 368 369 ParkEventLoop(); 370 } 371 372 void 373 CreateExecutionEnvironment(int *pargc, char ***pargv, 374 char jrepath[], jint so_jrepath, 375 char jvmpath[], jint so_jvmpath, 376 char jvmcfg[], jint so_jvmcfg) { 377 /* 378 * First, determine if we are running the desired data model. If we 379 * are running the desired data model, all the error messages 380 * associated with calling GetJREPath, ReadKnownVMs, etc. should be 381 * output. However, if we are not running the desired data model, 382 * some of the errors should be suppressed since it is more 383 * informative to issue an error message based on whether or not the 384 * os/processor combination has dual mode capabilities. 385 */ 386 jboolean jvmpathExists; 387 388 /* Compute/set the name of the executable */ 389 SetExecname(*pargv); 390 391 /* Check data model flags, and exec process, if needed */ 392 { 393 char *arch = (char *)GetArch(); /* like sparc or sparcv9 */ 394 char * jvmtype = NULL; 395 int argc = *pargc; 396 char **argv = *pargv; 397 int running = CURRENT_DATA_MODEL; 398 399 int wanted = running; /* What data mode is being 400 asked for? Current model is 401 fine unless another model 402 is asked for */ 403 404 char** newargv = NULL; 405 int newargc = 0; 406 407 /* 408 * Starting in 1.5, all unix platforms accept the -d32 and -d64 409 * options. On platforms where only one data-model is supported 410 * (e.g. ia-64 Linux), using the flag for the other data model is 411 * an error and will terminate the program. 412 */ 413 414 { /* open new scope to declare local variables */ 415 int i; 416 417 newargv = (char **)JLI_MemAlloc((argc+1) * sizeof(char*)); 418 newargv[newargc++] = argv[0]; 419 420 /* scan for data model arguments and remove from argument list; 421 last occurrence determines desired data model */ 422 for (i=1; i < argc; i++) { 423 424 if (JLI_StrCmp(argv[i], "-J-d64") == 0 || JLI_StrCmp(argv[i], "-d64") == 0) { 425 wanted = 64; 426 continue; 427 } 428 if (JLI_StrCmp(argv[i], "-J-d32") == 0 || JLI_StrCmp(argv[i], "-d32") == 0) { 429 wanted = 32; 430 continue; 431 } 432 newargv[newargc++] = argv[i]; 433 434 if (IsJavaArgs()) { 435 if (argv[i][0] != '-') continue; 436 } else { 437 if (JLI_StrCmp(argv[i], "-classpath") == 0 || JLI_StrCmp(argv[i], "-cp") == 0) { 438 i++; 439 if (i >= argc) break; 440 newargv[newargc++] = argv[i]; 441 continue; 442 } 443 if (argv[i][0] != '-') { i++; break; } 444 } 445 } 446 447 /* copy rest of args [i .. argc) */ 448 while (i < argc) { 449 newargv[newargc++] = argv[i++]; 450 } 451 newargv[newargc] = NULL; 452 453 /* 454 * newargv has all proper arguments here 455 */ 456 457 argc = newargc; 458 argv = newargv; 459 } 460 461 /* If the data model is not changing, it is an error if the 462 jvmpath does not exist */ 463 if (wanted == running) { 464 /* Find out where the JRE is that we will be using. */ 465 if (!GetJREPath(jrepath, so_jrepath, arch, JNI_FALSE) ) { 466 JLI_ReportErrorMessage(JRE_ERROR1); 467 exit(2); 468 } 469 JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%s%s%sjvm.cfg", 470 jrepath, FILESEP, FILESEP, "", ""); 471 /* Find the specified JVM type */ 472 if (ReadKnownVMs(jvmcfg, JNI_FALSE) < 1) { 473 JLI_ReportErrorMessage(CFG_ERROR7); 474 exit(1); 475 } 476 477 jvmpath[0] = '\0'; 478 jvmtype = CheckJvmType(pargc, pargv, JNI_FALSE); 479 if (JLI_StrCmp(jvmtype, "ERROR") == 0) { 480 JLI_ReportErrorMessage(CFG_ERROR9); 481 exit(4); 482 } 483 484 if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, arch, wanted)) { 485 JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath); 486 exit(4); 487 } 488 489 /* 490 * Mac OS X requires the Cocoa event loop to be run on the "main" 491 * thread. Spawn off a new thread to run main() and pass 492 * this thread off to the Cocoa event loop. 493 */ 494 MacOSXStartup(argc, argv); 495 496 /* 497 * we seem to have everything we need, so without further ado 498 * we return back, otherwise proceed to set the environment. 499 */ 500 return; 501 } else { /* do the same speculatively or exit */ 502 #if defined(DUAL_MODE) 503 if (running != wanted) { 504 /* Find out where the JRE is that we will be using. */ 505 if (!GetJREPath(jrepath, so_jrepath, GetArchPath(wanted), JNI_TRUE)) { 506 /* give up and let other code report error message */ 507 JLI_ReportErrorMessage(JRE_ERROR2, wanted); 508 exit(1); 509 } 510 JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%s%s%sjvm.cfg", 511 jrepath, FILESEP, FILESEP, "", ""); 512 /* 513 * Read in jvm.cfg for target data model and process vm 514 * selection options. 515 */ 516 if (ReadKnownVMs(jvmcfg, JNI_TRUE) < 1) { 517 /* give up and let other code report error message */ 518 JLI_ReportErrorMessage(JRE_ERROR2, wanted); 519 exit(1); 520 } 521 jvmpath[0] = '\0'; 522 jvmtype = CheckJvmType(pargc, pargv, JNI_TRUE); 523 if (JLI_StrCmp(jvmtype, "ERROR") == 0) { 524 JLI_ReportErrorMessage(CFG_ERROR9); 525 exit(4); 526 } 527 528 /* exec child can do error checking on the existence of the path */ 529 jvmpathExists = GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, GetArchPath(wanted), wanted); 530 } 531 #else /* ! DUAL_MODE */ 532 JLI_ReportErrorMessage(JRE_ERROR2, wanted); 533 exit(1); 534 #endif /* DUAL_MODE */ 535 } 536 { 537 char *newexec = execname; 538 JLI_TraceLauncher("TRACER_MARKER:About to EXEC\n"); 539 (void) fflush(stdout); 540 (void) fflush(stderr); 541 /* 542 * Use posix_spawn() instead of execv() on Mac OS X. 543 * This allows us to choose which architecture the child process 544 * should run as. 545 */ 546 { 547 posix_spawnattr_t attr; 548 size_t unused_size; 549 pid_t unused_pid; 550 551 #if defined(__i386__) || defined(__x86_64__) 552 cpu_type_t cpu_type[] = { (wanted == 64) ? CPU_TYPE_X86_64 : CPU_TYPE_X86, 553 (running== 64) ? CPU_TYPE_X86_64 : CPU_TYPE_X86 }; 554 #else 555 cpu_type_t cpu_type[] = { CPU_TYPE_ANY }; 556 #endif /* __i386 .. */ 557 558 posix_spawnattr_init(&attr); 559 posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETEXEC); 560 posix_spawnattr_setbinpref_np(&attr, sizeof(cpu_type) / sizeof(cpu_type_t), 561 cpu_type, &unused_size); 562 563 posix_spawn(&unused_pid, newexec, NULL, &attr, argv, environ); 564 } 565 JLI_ReportErrorMessageSys(JRE_ERROR4, newexec); 566 567 #if defined(DUAL_MODE) 568 if (running != wanted) { 569 JLI_ReportErrorMessage(JRE_ERROR5, wanted, running); 570 } 571 #endif /* DUAL_MODE */ 572 } 573 exit(1); 574 } 575 } 576 577 /* 578 * VM choosing is done by the launcher (java.c). 579 */ 580 static jboolean 581 GetJVMPath(const char *jrepath, const char *jvmtype, 582 char *jvmpath, jint jvmpathsize, const char * arch, int bitsWanted) 583 { 584 struct stat s; 585 586 if (JLI_StrChr(jvmtype, '/')) { 587 JLI_Snprintf(jvmpath, jvmpathsize, "%s/" JVM_DLL, jvmtype); 588 } else { 589 /* 590 * macosx client library is built thin, i386 only. 591 * 64 bit client requests must load server library 592 */ 593 const char *jvmtypeUsed = ((bitsWanted == 64) && (strcmp(jvmtype, "client") == 0)) ? "server" : jvmtype; 594 JLI_Snprintf(jvmpath, jvmpathsize, "%s/lib/%s/" JVM_DLL, jrepath, jvmtypeUsed); 595 } 596 597 JLI_TraceLauncher("Does `%s' exist ... ", jvmpath); 598 599 #ifdef STATIC_BUILD 600 return JNI_TRUE; 601 #else 602 if (stat(jvmpath, &s) == 0) { 603 JLI_TraceLauncher("yes.\n"); 604 return JNI_TRUE; 605 } else { 606 JLI_TraceLauncher("no.\n"); 607 return JNI_FALSE; 608 } 609 #endif 610 } 611 612 /* 613 * Find path to JRE based on .exe's location or registry settings. 614 */ 615 static jboolean 616 GetJREPath(char *path, jint pathsize, const char * arch, jboolean speculative) 617 { 618 char libjava[MAXPATHLEN]; 619 620 if (GetApplicationHome(path, pathsize)) { 621 /* Is JRE co-located with the application? */ 622 #ifdef STATIC_BUILD 623 char jvm_cfg[MAXPATHLEN]; 624 JLI_Snprintf(jvm_cfg, sizeof(jvm_cfg), "%s/lib/jvm.cfg", path); 625 if (access(jvm_cfg, F_OK) == 0) { 626 return JNI_TRUE; 627 } 628 #else 629 JLI_Snprintf(libjava, sizeof(libjava), "%s/lib/" JAVA_DLL, path); 630 if (access(libjava, F_OK) == 0) { 631 return JNI_TRUE; 632 } 633 #endif 634 /* ensure storage for path + /jre + NULL */ 635 if ((JLI_StrLen(path) + 4 + 1) > (size_t) pathsize) { 636 JLI_TraceLauncher("Insufficient space to store JRE path\n"); 637 return JNI_FALSE; 638 } 639 /* Does the app ship a private JRE in <apphome>/jre directory? */ 640 JLI_Snprintf(libjava, sizeof(libjava), "%s/jre/lib/" JAVA_DLL, path); 641 if (access(libjava, F_OK) == 0) { 642 JLI_StrCat(path, "/jre"); 643 JLI_TraceLauncher("JRE path is %s\n", path); 644 return JNI_TRUE; 645 } 646 } 647 648 /* try to find ourselves instead */ 649 Dl_info selfInfo; 650 dladdr(&GetJREPath, &selfInfo); 651 652 #ifdef STATIC_BUILD 653 char jvm_cfg[MAXPATHLEN]; 654 char *p = NULL; 655 strncpy(jvm_cfg, selfInfo.dli_fname, MAXPATHLEN); 656 p = strrchr(jvm_cfg, '/'); *p = '\0'; 657 p = strrchr(jvm_cfg, '/'); 658 if (strcmp(p, "/.") == 0) { 659 *p = '\0'; 660 p = strrchr(jvm_cfg, '/'); *p = '\0'; 661 } 662 else *p = '\0'; 663 strncpy(path, jvm_cfg, pathsize); 664 strncat(jvm_cfg, "/lib/jvm.cfg", MAXPATHLEN); 665 if (access(jvm_cfg, F_OK) == 0) { 666 return JNI_TRUE; 667 } 668 #endif 669 670 char *realPathToSelf = realpath(selfInfo.dli_fname, path); 671 if (realPathToSelf != path) { 672 return JNI_FALSE; 673 } 674 675 size_t pathLen = strlen(realPathToSelf); 676 if (pathLen == 0) { 677 return JNI_FALSE; 678 } 679 680 const char lastPathComponent[] = "/lib/jli/libjli.dylib"; 681 size_t sizeOfLastPathComponent = sizeof(lastPathComponent) - 1; 682 if (pathLen < sizeOfLastPathComponent) { 683 return JNI_FALSE; 684 } 685 686 size_t indexOfLastPathComponent = pathLen - sizeOfLastPathComponent; 687 if (0 == strncmp(realPathToSelf + indexOfLastPathComponent, lastPathComponent, sizeOfLastPathComponent - 1)) { 688 realPathToSelf[indexOfLastPathComponent + 1] = '\0'; 689 return JNI_TRUE; 690 } 691 692 if (!speculative) 693 JLI_ReportErrorMessage(JRE_ERROR8 JAVA_DLL); 694 return JNI_FALSE; 695 } 696 697 jboolean 698 LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn) 699 { 700 Dl_info dlinfo; 701 void *libjvm; 702 703 JLI_TraceLauncher("JVM path is %s\n", jvmpath); 704 705 #ifndef STATIC_BUILD 706 libjvm = dlopen(jvmpath, RTLD_NOW + RTLD_GLOBAL); 707 #else 708 libjvm = dlopen(NULL, RTLD_FIRST); 709 #endif 710 if (libjvm == NULL) { 711 JLI_ReportErrorMessage(DLL_ERROR1, __LINE__); 712 JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); 713 return JNI_FALSE; 714 } 715 716 ifn->CreateJavaVM = (CreateJavaVM_t) 717 dlsym(libjvm, "JNI_CreateJavaVM"); 718 if (ifn->CreateJavaVM == NULL) { 719 JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); 720 return JNI_FALSE; 721 } 722 723 ifn->GetDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs_t) 724 dlsym(libjvm, "JNI_GetDefaultJavaVMInitArgs"); 725 if (ifn->GetDefaultJavaVMInitArgs == NULL) { 726 JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); 727 return JNI_FALSE; 728 } 729 730 ifn->GetCreatedJavaVMs = (GetCreatedJavaVMs_t) 731 dlsym(libjvm, "JNI_GetCreatedJavaVMs"); 732 if (ifn->GetCreatedJavaVMs == NULL) { 733 JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); 734 return JNI_FALSE; 735 } 736 737 return JNI_TRUE; 738 } 739 740 /* 741 * Compute the name of the executable 742 * 743 * In order to re-exec securely we need the absolute path of the 744 * executable. On Solaris getexecname(3c) may not return an absolute 745 * path so we use dladdr to get the filename of the executable and 746 * then use realpath to derive an absolute path. From Solaris 9 747 * onwards the filename returned in DL_info structure from dladdr is 748 * an absolute pathname so technically realpath isn't required. 749 * On Linux we read the executable name from /proc/self/exe. 750 * As a fallback, and for platforms other than Solaris and Linux, 751 * we use FindExecName to compute the executable name. 752 */ 753 const char* 754 SetExecname(char **argv) 755 { 756 char* exec_path = NULL; 757 { 758 Dl_info dlinfo; 759 760 #ifdef STATIC_BUILD 761 void *fptr; 762 fptr = (void *)&SetExecname; 763 #else 764 int (*fptr)(); 765 fptr = (int (*)())dlsym(RTLD_DEFAULT, "main"); 766 #endif 767 if (fptr == NULL) { 768 JLI_ReportErrorMessage(DLL_ERROR3, dlerror()); 769 return JNI_FALSE; 770 } 771 772 if (dladdr((void*)fptr, &dlinfo)) { 773 char *resolved = (char*)JLI_MemAlloc(PATH_MAX+1); 774 if (resolved != NULL) { 775 exec_path = realpath(dlinfo.dli_fname, resolved); 776 if (exec_path == NULL) { 777 JLI_MemFree(resolved); 778 } 779 } 780 } 781 } 782 if (exec_path == NULL) { 783 exec_path = FindExecName(argv[0]); 784 } 785 execname = exec_path; 786 return exec_path; 787 } 788 789 /* 790 * BSD's implementation of CounterGet() 791 */ 792 int64_t 793 CounterGet() 794 { 795 struct timeval tv; 796 gettimeofday(&tv, NULL); 797 return (tv.tv_sec * 1000) + tv.tv_usec; 798 } 799 800 801 /* --- Splash Screen shared library support --- */ 802 803 static JavaVM* SetJavaVMValue() 804 { 805 JavaVM * jvm = NULL; 806 807 // The handle is good for both the launcher and the libosxapp.dylib 808 void * handle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL); 809 if (handle) { 810 typedef JavaVM* (*JLI_GetJavaVMInstance_t)(); 811 812 JLI_GetJavaVMInstance_t JLI_GetJavaVMInstance = 813 (JLI_GetJavaVMInstance_t)dlsym(handle, 814 "JLI_GetJavaVMInstance"); 815 if (JLI_GetJavaVMInstance) { 816 jvm = JLI_GetJavaVMInstance(); 817 } 818 819 if (jvm) { 820 typedef void (*OSXAPP_SetJavaVM_t)(JavaVM*); 821 822 OSXAPP_SetJavaVM_t OSXAPP_SetJavaVM = 823 (OSXAPP_SetJavaVM_t)dlsym(handle, "OSXAPP_SetJavaVM"); 824 if (OSXAPP_SetJavaVM) { 825 OSXAPP_SetJavaVM(jvm); 826 } else { 827 jvm = NULL; 828 } 829 } 830 831 dlclose(handle); 832 } 833 834 return jvm; 835 } 836 837 static const char* SPLASHSCREEN_SO = JNI_LIB_NAME("splashscreen"); 838 839 static void* hSplashLib = NULL; 840 841 void* SplashProcAddress(const char* name) { 842 if (!hSplashLib) { 843 char jrePath[PATH_MAX]; 844 if (!GetJREPath(jrePath, sizeof(jrePath), GetArch(), JNI_FALSE)) { 845 JLI_ReportErrorMessage(JRE_ERROR1); 846 return NULL; 847 } 848 849 char splashPath[PATH_MAX]; 850 const int ret = JLI_Snprintf(splashPath, sizeof(splashPath), 851 "%s/lib/%s", jrePath, SPLASHSCREEN_SO); 852 if (ret >= (int)sizeof(splashPath)) { 853 JLI_ReportErrorMessage(JRE_ERROR11); 854 return NULL; 855 } 856 if (ret < 0) { 857 JLI_ReportErrorMessage(JRE_ERROR13); 858 return NULL; 859 } 860 861 hSplashLib = dlopen(splashPath, RTLD_LAZY | RTLD_GLOBAL); 862 // It's OK if dlopen() fails. The splash screen library binary file 863 // might have been stripped out from the JRE image to reduce its size 864 // (e.g. on embedded platforms). 865 866 if (hSplashLib) { 867 if (!SetJavaVMValue()) { 868 dlclose(hSplashLib); 869 hSplashLib = NULL; 870 } 871 } 872 } 873 if (hSplashLib) { 874 void* sym = dlsym(hSplashLib, name); 875 return sym; 876 } else { 877 return NULL; 878 } 879 } 880 881 void SplashFreeLibrary() { 882 if (hSplashLib) { 883 dlclose(hSplashLib); 884 hSplashLib = NULL; 885 } 886 } 887 888 /* 889 * Block current thread and continue execution in a new thread 890 */ 891 int 892 ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void * args) { 893 int rslt; 894 pthread_t tid; 895 pthread_attr_t attr; 896 pthread_attr_init(&attr); 897 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); 898 899 if (stack_size > 0) { 900 pthread_attr_setstacksize(&attr, stack_size); 901 } 902 903 if (pthread_create(&tid, &attr, (void *(*)(void*))continuation, (void*)args) == 0) { 904 void * tmp; 905 pthread_join(tid, &tmp); 906 rslt = (int)(intptr_t)tmp; 907 } else { 908 /* 909 * Continue execution in current thread if for some reason (e.g. out of 910 * memory/LWP) a new thread can't be created. This will likely fail 911 * later in continuation as JNI_CreateJavaVM needs to create quite a 912 * few new threads, anyway, just give it a try.. 913 */ 914 rslt = continuation(args); 915 } 916 917 pthread_attr_destroy(&attr); 918 return rslt; 919 } 920 921 void SetJavaLauncherPlatformProps() { 922 /* Linux only */ 923 } 924 925 jboolean 926 ServerClassMachine(void) { 927 return JNI_TRUE; 928 } 929 930 static JavaVM* jvmInstance = NULL; 931 static jboolean sameThread = JNI_FALSE; /* start VM in current thread */ 932 933 /* 934 * Note there is a callback on this function from the splashscreen logic, 935 * this as well SetJavaVMValue() needs to be simplified. 936 */ 937 JavaVM* 938 JLI_GetJavaVMInstance() 939 { 940 return jvmInstance; 941 } 942 943 void 944 RegisterThread() 945 { 946 objc_registerThreadWithCollector(); 947 } 948 949 static void 950 SetXDockArgForAWT(const char *arg) 951 { 952 char envVar[80]; 953 if (strstr(arg, "-Xdock:name=") == arg) { 954 /* 955 * The APP_NAME_<pid> environment variable is used to pass 956 * an application name as specified with the -Xdock:name command 957 * line option from Java launcher code to the AWT code in order 958 * to assign this name to the app's dock tile on the Mac. 959 * The _<pid> part is added to avoid collisions with child processes. 960 * 961 * WARNING: This environment variable is an implementation detail and 962 * isn't meant for use outside of the core platform. The mechanism for 963 * passing this information from Java launcher to other modules may 964 * change drastically between update release, and it may even be 965 * removed or replaced with another mechanism. 966 * 967 * NOTE: It is used by SWT, and JavaFX. 968 */ 969 snprintf(envVar, sizeof(envVar), "APP_NAME_%d", getpid()); 970 setenv(envVar, (arg + 12), 1); 971 } 972 973 if (strstr(arg, "-Xdock:icon=") == arg) { 974 /* 975 * The APP_ICON_<pid> environment variable is used to pass 976 * an application icon as specified with the -Xdock:icon command 977 * line option from Java launcher code to the AWT code in order 978 * to assign this icon to the app's dock tile on the Mac. 979 * The _<pid> part is added to avoid collisions with child processes. 980 * 981 * WARNING: This environment variable is an implementation detail and 982 * isn't meant for use outside of the core platform. The mechanism for 983 * passing this information from Java launcher to other modules may 984 * change drastically between update release, and it may even be 985 * removed or replaced with another mechanism. 986 * 987 * NOTE: It is used by SWT, and JavaFX. 988 */ 989 snprintf(envVar, sizeof(envVar), "APP_ICON_%d", getpid()); 990 setenv(envVar, (arg + 12), 1); 991 } 992 } 993 994 static void 995 SetMainClassForAWT(JNIEnv *env, jclass mainClass) { 996 jclass classClass = NULL; 997 NULL_CHECK(classClass = FindBootStrapClass(env, "java/lang/Class")); 998 999 jmethodID getCanonicalNameMID = NULL; 1000 NULL_CHECK(getCanonicalNameMID = (*env)->GetMethodID(env, classClass, "getCanonicalName", "()Ljava/lang/String;")); 1001 1002 jstring mainClassString = (*env)->CallObjectMethod(env, mainClass, getCanonicalNameMID); 1003 if ((*env)->ExceptionCheck(env)) { 1004 /* 1005 * Clears all errors caused by getCanonicalName() on the mainclass and 1006 * leaves the JAVA_MAIN_CLASS__<pid> empty. 1007 */ 1008 (*env)->ExceptionClear(env); 1009 return; 1010 } 1011 1012 const char *mainClassName = NULL; 1013 NULL_CHECK(mainClassName = (*env)->GetStringUTFChars(env, mainClassString, NULL)); 1014 1015 char envVar[80]; 1016 /* 1017 * The JAVA_MAIN_CLASS_<pid> environment variable is used to pass 1018 * the name of a Java class whose main() method is invoked by 1019 * the Java launcher code to start the application, to the AWT code 1020 * in order to assign the name to the Apple menu bar when the app 1021 * is active on the Mac. 1022 * The _<pid> part is added to avoid collisions with child processes. 1023 * 1024 * WARNING: This environment variable is an implementation detail and 1025 * isn't meant for use outside of the core platform. The mechanism for 1026 * passing this information from Java launcher to other modules may 1027 * change drastically between update release, and it may even be 1028 * removed or replaced with another mechanism. 1029 * 1030 * NOTE: It is used by SWT, and JavaFX. 1031 */ 1032 snprintf(envVar, sizeof(envVar), "JAVA_MAIN_CLASS_%d", getpid()); 1033 setenv(envVar, mainClassName, 1); 1034 1035 (*env)->ReleaseStringUTFChars(env, mainClassString, mainClassName); 1036 } 1037 1038 void 1039 SetXStartOnFirstThreadArg() 1040 { 1041 // XXX: BEGIN HACK 1042 // short circuit hack for <https://bugs.eclipse.org/bugs/show_bug.cgi?id=211625> 1043 // need a way to get AWT/Swing apps launched when spawned from Eclipse, 1044 // which currently has no UI to not pass the -XstartOnFirstThread option 1045 if (getenv("HACK_IGNORE_START_ON_FIRST_THREAD") != NULL) return; 1046 // XXX: END HACK 1047 1048 sameThread = JNI_TRUE; 1049 // Set a variable that tells us we started on the main thread. 1050 // This is used by the AWT during startup. (See LWCToolkit.m) 1051 char envVar[80]; 1052 snprintf(envVar, sizeof(envVar), "JAVA_STARTED_ON_FIRST_THREAD_%d", getpid()); 1053 setenv(envVar, "1", 1); 1054 } 1055 1056 /* This class is made for performSelectorOnMainThread when java main 1057 * should be launched on main thread. 1058 * We cannot use dispatch_sync here, because it blocks the main dispatch queue 1059 * which is used inside Cocoa 1060 */ 1061 @interface JavaLaunchHelper : NSObject { 1062 int _returnValue; 1063 } 1064 - (void) launchJava:(NSValue*)argsValue; 1065 - (int) getReturnValue; 1066 @end 1067 1068 @implementation JavaLaunchHelper 1069 1070 - (void) launchJava:(NSValue*)argsValue 1071 { 1072 _returnValue = JavaMain([argsValue pointerValue]); 1073 } 1074 1075 - (int) getReturnValue 1076 { 1077 return _returnValue; 1078 } 1079 1080 @end 1081 1082 // MacOSX we may continue in the same thread 1083 int 1084 JVMInit(InvocationFunctions* ifn, jlong threadStackSize, 1085 int argc, char **argv, 1086 int mode, char *what, int ret) { 1087 if (sameThread) { 1088 JLI_TraceLauncher("In same thread\n"); 1089 // need to block this thread against the main thread 1090 // so signals get caught correctly 1091 JavaMainArgs args; 1092 args.argc = argc; 1093 args.argv = argv; 1094 args.mode = mode; 1095 args.what = what; 1096 args.ifn = *ifn; 1097 int rslt; 1098 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 1099 { 1100 JavaLaunchHelper* launcher = [[[JavaLaunchHelper alloc] init] autorelease]; 1101 [launcher performSelectorOnMainThread:@selector(launchJava:) 1102 withObject:[NSValue valueWithPointer:(void*)&args] 1103 waitUntilDone:YES]; 1104 rslt = [launcher getReturnValue]; 1105 } 1106 [pool drain]; 1107 return rslt; 1108 } else { 1109 return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret); 1110 } 1111 } 1112 1113 /* 1114 * Note the jvmInstance must be initialized first before entering into 1115 * ShowSplashScreen, as there is a callback into the JLI_GetJavaVMInstance. 1116 */ 1117 void PostJVMInit(JNIEnv *env, jclass mainClass, JavaVM *vm) { 1118 jvmInstance = vm; 1119 SetMainClassForAWT(env, mainClass); 1120 CHECK_EXCEPTION_RETURN(); 1121 ShowSplashScreen(); 1122 } 1123 1124 jboolean 1125 ProcessPlatformOption(const char* arg) 1126 { 1127 if (JLI_StrCmp(arg, "-XstartOnFirstThread") == 0) { 1128 SetXStartOnFirstThreadArg(); 1129 return JNI_TRUE; 1130 } else if (JLI_StrCCmp(arg, "-Xdock:") == 0) { 1131 SetXDockArgForAWT(arg); 1132 return JNI_TRUE; 1133 } 1134 // arguments we know not 1135 return JNI_FALSE; 1136 }