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 ifn->GetCreatedJavaVMs = (SetNativeThreadName0_t) 738 dlsym(libjvm, "JVM_SetNativeThreadName0"); 739 if (ifn->GetCreatedJavaVMs == NULL) { 740 JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror()); 741 return JNI_FALSE; 742 } 743 744 return JNI_TRUE; 745 } 746 747 /* 748 * Compute the name of the executable 749 * 750 * In order to re-exec securely we need the absolute path of the 751 * executable. On Solaris getexecname(3c) may not return an absolute 752 * path so we use dladdr to get the filename of the executable and 753 * then use realpath to derive an absolute path. From Solaris 9 754 * onwards the filename returned in DL_info structure from dladdr is 755 * an absolute pathname so technically realpath isn't required. 756 * On Linux we read the executable name from /proc/self/exe. 757 * As a fallback, and for platforms other than Solaris and Linux, 758 * we use FindExecName to compute the executable name. 759 */ 760 const char* 761 SetExecname(char **argv) 762 { 763 char* exec_path = NULL; 764 { 765 Dl_info dlinfo; 766 767 #ifdef STATIC_BUILD 768 void *fptr; 769 fptr = (void *)&SetExecname; 770 #else 771 int (*fptr)(); 772 fptr = (int (*)())dlsym(RTLD_DEFAULT, "main"); 773 #endif 774 if (fptr == NULL) { 775 JLI_ReportErrorMessage(DLL_ERROR3, dlerror()); 776 return JNI_FALSE; 777 } 778 779 if (dladdr((void*)fptr, &dlinfo)) { 780 char *resolved = (char*)JLI_MemAlloc(PATH_MAX+1); 781 if (resolved != NULL) { 782 exec_path = realpath(dlinfo.dli_fname, resolved); 783 if (exec_path == NULL) { 784 JLI_MemFree(resolved); 785 } 786 } 787 } 788 } 789 if (exec_path == NULL) { 790 exec_path = FindExecName(argv[0]); 791 } 792 execname = exec_path; 793 return exec_path; 794 } 795 796 /* 797 * BSD's implementation of CounterGet() 798 */ 799 int64_t 800 CounterGet() 801 { 802 struct timeval tv; 803 gettimeofday(&tv, NULL); 804 return (tv.tv_sec * 1000) + tv.tv_usec; 805 } 806 807 808 /* --- Splash Screen shared library support --- */ 809 810 static JavaVM* SetJavaVMValue() 811 { 812 JavaVM * jvm = NULL; 813 814 // The handle is good for both the launcher and the libosxapp.dylib 815 void * handle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL); 816 if (handle) { 817 typedef JavaVM* (*JLI_GetJavaVMInstance_t)(); 818 819 JLI_GetJavaVMInstance_t JLI_GetJavaVMInstance = 820 (JLI_GetJavaVMInstance_t)dlsym(handle, 821 "JLI_GetJavaVMInstance"); 822 if (JLI_GetJavaVMInstance) { 823 jvm = JLI_GetJavaVMInstance(); 824 } 825 826 if (jvm) { 827 typedef void (*OSXAPP_SetJavaVM_t)(JavaVM*); 828 829 OSXAPP_SetJavaVM_t OSXAPP_SetJavaVM = 830 (OSXAPP_SetJavaVM_t)dlsym(handle, "OSXAPP_SetJavaVM"); 831 if (OSXAPP_SetJavaVM) { 832 OSXAPP_SetJavaVM(jvm); 833 } else { 834 jvm = NULL; 835 } 836 } 837 838 dlclose(handle); 839 } 840 841 return jvm; 842 } 843 844 static const char* SPLASHSCREEN_SO = JNI_LIB_NAME("splashscreen"); 845 846 static void* hSplashLib = NULL; 847 848 void* SplashProcAddress(const char* name) { 849 if (!hSplashLib) { 850 char jrePath[PATH_MAX]; 851 if (!GetJREPath(jrePath, sizeof(jrePath), GetArch(), JNI_FALSE)) { 852 JLI_ReportErrorMessage(JRE_ERROR1); 853 return NULL; 854 } 855 856 char splashPath[PATH_MAX]; 857 const int ret = JLI_Snprintf(splashPath, sizeof(splashPath), 858 "%s/lib/%s", jrePath, SPLASHSCREEN_SO); 859 if (ret >= (int)sizeof(splashPath)) { 860 JLI_ReportErrorMessage(JRE_ERROR11); 861 return NULL; 862 } 863 if (ret < 0) { 864 JLI_ReportErrorMessage(JRE_ERROR13); 865 return NULL; 866 } 867 868 hSplashLib = dlopen(splashPath, RTLD_LAZY | RTLD_GLOBAL); 869 // It's OK if dlopen() fails. The splash screen library binary file 870 // might have been stripped out from the JRE image to reduce its size 871 // (e.g. on embedded platforms). 872 873 if (hSplashLib) { 874 if (!SetJavaVMValue()) { 875 dlclose(hSplashLib); 876 hSplashLib = NULL; 877 } 878 } 879 } 880 if (hSplashLib) { 881 void* sym = dlsym(hSplashLib, name); 882 return sym; 883 } else { 884 return NULL; 885 } 886 } 887 888 void SplashFreeLibrary() { 889 if (hSplashLib) { 890 dlclose(hSplashLib); 891 hSplashLib = NULL; 892 } 893 } 894 895 /* 896 * Block current thread and continue execution in a new thread 897 */ 898 int 899 ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void * args) { 900 int rslt; 901 pthread_t tid; 902 pthread_attr_t attr; 903 pthread_attr_init(&attr); 904 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); 905 906 if (stack_size > 0) { 907 pthread_attr_setstacksize(&attr, stack_size); 908 } 909 910 if (pthread_create(&tid, &attr, (void *(*)(void*))continuation, (void*)args) == 0) { 911 void * tmp; 912 pthread_join(tid, &tmp); 913 rslt = (int)(intptr_t)tmp; 914 } else { 915 /* 916 * Continue execution in current thread if for some reason (e.g. out of 917 * memory/LWP) a new thread can't be created. This will likely fail 918 * later in continuation as JNI_CreateJavaVM needs to create quite a 919 * few new threads, anyway, just give it a try.. 920 */ 921 rslt = continuation(args); 922 } 923 924 pthread_attr_destroy(&attr); 925 return rslt; 926 } 927 928 void SetJavaLauncherPlatformProps() { 929 /* Linux only */ 930 } 931 932 jboolean 933 ServerClassMachine(void) { 934 return JNI_TRUE; 935 } 936 937 static JavaVM* jvmInstance = NULL; 938 static jboolean sameThread = JNI_FALSE; /* start VM in current thread */ 939 940 /* 941 * Note there is a callback on this function from the splashscreen logic, 942 * this as well SetJavaVMValue() needs to be simplified. 943 */ 944 JavaVM* 945 JLI_GetJavaVMInstance() 946 { 947 return jvmInstance; 948 } 949 950 void 951 RegisterThread() 952 { 953 objc_registerThreadWithCollector(); 954 } 955 956 static void 957 SetXDockArgForAWT(const char *arg) 958 { 959 char envVar[80]; 960 if (strstr(arg, "-Xdock:name=") == arg) { 961 /* 962 * The APP_NAME_<pid> environment variable is used to pass 963 * an application name as specified with the -Xdock:name command 964 * line option from Java launcher code to the AWT code in order 965 * to assign this name to the app's dock tile on the Mac. 966 * The _<pid> part is added to avoid collisions with child processes. 967 * 968 * WARNING: This environment variable is an implementation detail and 969 * isn't meant for use outside of the core platform. The mechanism for 970 * passing this information from Java launcher to other modules may 971 * change drastically between update release, and it may even be 972 * removed or replaced with another mechanism. 973 * 974 * NOTE: It is used by SWT, and JavaFX. 975 */ 976 snprintf(envVar, sizeof(envVar), "APP_NAME_%d", getpid()); 977 setenv(envVar, (arg + 12), 1); 978 } 979 980 if (strstr(arg, "-Xdock:icon=") == arg) { 981 /* 982 * The APP_ICON_<pid> environment variable is used to pass 983 * an application icon as specified with the -Xdock:icon command 984 * line option from Java launcher code to the AWT code in order 985 * to assign this icon to the app's dock tile on the Mac. 986 * The _<pid> part is added to avoid collisions with child processes. 987 * 988 * WARNING: This environment variable is an implementation detail and 989 * isn't meant for use outside of the core platform. The mechanism for 990 * passing this information from Java launcher to other modules may 991 * change drastically between update release, and it may even be 992 * removed or replaced with another mechanism. 993 * 994 * NOTE: It is used by SWT, and JavaFX. 995 */ 996 snprintf(envVar, sizeof(envVar), "APP_ICON_%d", getpid()); 997 setenv(envVar, (arg + 12), 1); 998 } 999 } 1000 1001 static void 1002 SetMainClassForAWT(JNIEnv *env, jclass mainClass) { 1003 jclass classClass = NULL; 1004 NULL_CHECK(classClass = FindBootStrapClass(env, "java/lang/Class")); 1005 1006 jmethodID getCanonicalNameMID = NULL; 1007 NULL_CHECK(getCanonicalNameMID = (*env)->GetMethodID(env, classClass, "getCanonicalName", "()Ljava/lang/String;")); 1008 1009 jstring mainClassString = (*env)->CallObjectMethod(env, mainClass, getCanonicalNameMID); 1010 if ((*env)->ExceptionCheck(env)) { 1011 /* 1012 * Clears all errors caused by getCanonicalName() on the mainclass and 1013 * leaves the JAVA_MAIN_CLASS__<pid> empty. 1014 */ 1015 (*env)->ExceptionClear(env); 1016 return; 1017 } 1018 1019 const char *mainClassName = NULL; 1020 NULL_CHECK(mainClassName = (*env)->GetStringUTFChars(env, mainClassString, NULL)); 1021 1022 char envVar[80]; 1023 /* 1024 * The JAVA_MAIN_CLASS_<pid> environment variable is used to pass 1025 * the name of a Java class whose main() method is invoked by 1026 * the Java launcher code to start the application, to the AWT code 1027 * in order to assign the name to the Apple menu bar when the app 1028 * is active on the Mac. 1029 * The _<pid> part is added to avoid collisions with child processes. 1030 * 1031 * WARNING: This environment variable is an implementation detail and 1032 * isn't meant for use outside of the core platform. The mechanism for 1033 * passing this information from Java launcher to other modules may 1034 * change drastically between update release, and it may even be 1035 * removed or replaced with another mechanism. 1036 * 1037 * NOTE: It is used by SWT, and JavaFX. 1038 */ 1039 snprintf(envVar, sizeof(envVar), "JAVA_MAIN_CLASS_%d", getpid()); 1040 setenv(envVar, mainClassName, 1); 1041 1042 (*env)->ReleaseStringUTFChars(env, mainClassString, mainClassName); 1043 } 1044 1045 void 1046 SetXStartOnFirstThreadArg() 1047 { 1048 // XXX: BEGIN HACK 1049 // short circuit hack for <https://bugs.eclipse.org/bugs/show_bug.cgi?id=211625> 1050 // need a way to get AWT/Swing apps launched when spawned from Eclipse, 1051 // which currently has no UI to not pass the -XstartOnFirstThread option 1052 if (getenv("HACK_IGNORE_START_ON_FIRST_THREAD") != NULL) return; 1053 // XXX: END HACK 1054 1055 sameThread = JNI_TRUE; 1056 // Set a variable that tells us we started on the main thread. 1057 // This is used by the AWT during startup. (See LWCToolkit.m) 1058 char envVar[80]; 1059 snprintf(envVar, sizeof(envVar), "JAVA_STARTED_ON_FIRST_THREAD_%d", getpid()); 1060 setenv(envVar, "1", 1); 1061 } 1062 1063 /* This class is made for performSelectorOnMainThread when java main 1064 * should be launched on main thread. 1065 * We cannot use dispatch_sync here, because it blocks the main dispatch queue 1066 * which is used inside Cocoa 1067 */ 1068 @interface JavaLaunchHelper : NSObject { 1069 int _returnValue; 1070 } 1071 - (void) launchJava:(NSValue*)argsValue; 1072 - (int) getReturnValue; 1073 @end 1074 1075 @implementation JavaLaunchHelper 1076 1077 - (void) launchJava:(NSValue*)argsValue 1078 { 1079 _returnValue = JavaMain([argsValue pointerValue]); 1080 } 1081 1082 - (int) getReturnValue 1083 { 1084 return _returnValue; 1085 } 1086 1087 @end 1088 1089 // MacOSX we may continue in the same thread 1090 int 1091 JVMInit(InvocationFunctions* ifn, jlong threadStackSize, 1092 int argc, char **argv, 1093 int mode, char *what, int ret) { 1094 if (sameThread) { 1095 JLI_TraceLauncher("In same thread\n"); 1096 // need to block this thread against the main thread 1097 // so signals get caught correctly 1098 JavaMainArgs args; 1099 args.argc = argc; 1100 args.argv = argv; 1101 args.mode = mode; 1102 args.what = what; 1103 args.ifn = *ifn; 1104 int rslt; 1105 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 1106 { 1107 JavaLaunchHelper* launcher = [[[JavaLaunchHelper alloc] init] autorelease]; 1108 [launcher performSelectorOnMainThread:@selector(launchJava:) 1109 withObject:[NSValue valueWithPointer:(void*)&args] 1110 waitUntilDone:YES]; 1111 rslt = [launcher getReturnValue]; 1112 } 1113 [pool drain]; 1114 return rslt; 1115 } else { 1116 return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret); 1117 } 1118 } 1119 1120 /* 1121 * Note the jvmInstance must be initialized first before entering into 1122 * ShowSplashScreen, as there is a callback into the JLI_GetJavaVMInstance. 1123 */ 1124 void PostJVMInit(JNIEnv *env, jclass mainClass, JavaVM *vm) { 1125 jvmInstance = vm; 1126 SetMainClassForAWT(env, mainClass); 1127 CHECK_EXCEPTION_RETURN(); 1128 ShowSplashScreen(); 1129 } 1130 1131 jboolean 1132 ProcessPlatformOption(const char* arg) 1133 { 1134 if (JLI_StrCmp(arg, "-XstartOnFirstThread") == 0) { 1135 SetXStartOnFirstThreadArg(); 1136 return JNI_TRUE; 1137 } else if (JLI_StrCCmp(arg, "-Xdock:") == 0) { 1138 SetXDockArgForAWT(arg); 1139 return JNI_TRUE; 1140 } 1141 // arguments we know not 1142 return JNI_FALSE; 1143 }