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 JNIEXPORT jint JNICALL
 249 JNI_GetDefaultJavaVMInitArgs(void *args) {
 250     InvocationFunctions *ifn = GetExportedJNIFunctions();
 251     if (ifn == NULL) return JNI_ERR;
 252     return ifn->GetDefaultJavaVMInitArgs(args);
 253 }
 254 
 255 JNIEXPORT jint JNICALL
 256 JNI_CreateJavaVM(JavaVM **pvm, void **penv, void *args) {
 257     InvocationFunctions *ifn = GetExportedJNIFunctions();
 258     if (ifn == NULL) return JNI_ERR;
 259     return ifn->CreateJavaVM(pvm, penv, args);
 260 }
 261 
 262 JNIEXPORT jint JNICALL
 263 JNI_GetCreatedJavaVMs(JavaVM **vmBuf, jsize bufLen, jsize *nVMs) {
 264     InvocationFunctions *ifn = GetExportedJNIFunctions();
 265     if (ifn == NULL) return JNI_ERR;
 266     return ifn->GetCreatedJavaVMs(vmBuf, bufLen, nVMs);
 267 }
 268 
 269 /*
 270  * Allow JLI-aware launchers to specify a client/server preference
 271  */
 272 JNIEXPORT void JNICALL
 273 JLI_SetPreferredJVM(const char *prefJVM) {
 274     if (sPreferredJVMType != NULL) {
 275         free(sPreferredJVMType);
 276         sPreferredJVMType = NULL;
 277     }
 278 
 279     if (prefJVM == NULL) return;
 280     sPreferredJVMType = strdup(prefJVM);
 281 }
 282 
 283 static BOOL awtLoaded = NO;
 284 static pthread_mutex_t awtLoaded_mutex = PTHREAD_MUTEX_INITIALIZER;
 285 static pthread_cond_t  awtLoaded_cv = PTHREAD_COND_INITIALIZER;
 286 
 287 JNIEXPORT void JNICALL
 288 JLI_NotifyAWTLoaded()
 289 {
 290     pthread_mutex_lock(&awtLoaded_mutex);
 291     awtLoaded = YES;
 292     pthread_cond_signal(&awtLoaded_cv);
 293     pthread_mutex_unlock(&awtLoaded_mutex);
 294 }
 295 
 296 static int (*main_fptr)(int argc, char **argv) = NULL;
 297 
 298 /*
 299  * Unwrap the arguments and re-run main()
 300  */
 301 static void *apple_main (void *arg)
 302 {
 303     objc_registerThreadWithCollector();
 304 
 305     if (main_fptr == NULL) {
 306         main_fptr = (int (*)())dlsym(RTLD_DEFAULT, "main");
 307         if (main_fptr == NULL) {
 308             JLI_ReportErrorMessageSys("error locating main entrypoint\n");
 309             exit(1);
 310         }
 311     }
 312 
 313     struct NSAppArgs *args = (struct NSAppArgs *) arg;
 314     exit(main_fptr(args->argc, args->argv));
 315 }
 316 
 317 static void dummyTimer(CFRunLoopTimerRef timer, void *info) {}
 318 
 319 static void ParkEventLoop() {
 320     // RunLoop needs at least one source, and 1e20 is pretty far into the future
 321     CFRunLoopTimerRef t = CFRunLoopTimerCreate(kCFAllocatorDefault, 1.0e20, 0.0, 0, 0, dummyTimer, NULL);
 322     CFRunLoopAddTimer(CFRunLoopGetCurrent(), t, kCFRunLoopDefaultMode);
 323     CFRelease(t);
 324 
 325     // Park this thread in the main run loop.
 326     int32_t result;
 327     do {
 328         result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e20, false);
 329     } while (result != kCFRunLoopRunFinished);
 330 }
 331 
 332 /*
 333  * Mac OS X mandates that the GUI event loop run on very first thread of
 334  * an application. This requires that we re-call Java's main() on a new
 335  * thread, reserving the 'main' thread for Cocoa.
 336  */
 337 static void MacOSXStartup(int argc, char *argv[]) {
 338     // Thread already started?
 339     static jboolean started = false;
 340     if (started) {
 341         return;
 342     }
 343     started = true;
 344 
 345     // Hand off arguments
 346     struct NSAppArgs args;
 347     args.argc = argc;
 348     args.argv = argv;
 349 
 350     // Fire up the main thread
 351     pthread_t main_thr;
 352     if (pthread_create(&main_thr, NULL, &apple_main, &args) != 0) {
 353         JLI_ReportErrorMessageSys("Could not create main thread: %s\n", strerror(errno));
 354         exit(1);
 355     }
 356     if (pthread_detach(main_thr)) {
 357         JLI_ReportErrorMessageSys("pthread_detach() failed: %s\n", strerror(errno));
 358         exit(1);
 359     }
 360 
 361     ParkEventLoop();
 362 }
 363 
 364 void
 365 CreateExecutionEnvironment(int *pargc, char ***pargv,
 366                            char jrepath[], jint so_jrepath,
 367                            char jvmpath[], jint so_jvmpath,
 368                            char jvmcfg[],  jint so_jvmcfg) {
 369   /*
 370    * First, determine if we are running the desired data model.  If we
 371    * are running the desired data model, all the error messages
 372    * associated with calling GetJREPath, ReadKnownVMs, etc. should be
 373    * output.  However, if we are not running the desired data model,
 374    * some of the errors should be suppressed since it is more
 375    * informative to issue an error message based on whether or not the
 376    * os/processor combination has dual mode capabilities.
 377    */
 378     jboolean jvmpathExists;
 379 
 380     /* Compute/set the name of the executable */
 381     SetExecname(*pargv);
 382 
 383     /* Check data model flags, and exec process, if needed */
 384     {
 385       char *arch        = (char *)GetArch(); /* like sparc or sparcv9 */
 386       char * jvmtype    = NULL;
 387       int  argc         = *pargc;
 388       char **argv       = *pargv;
 389       int running       = CURRENT_DATA_MODEL;
 390 
 391       int wanted        = running;      /* What data mode is being
 392                                            asked for? Current model is
 393                                            fine unless another model
 394                                            is asked for */
 395 
 396       char** newargv    = NULL;
 397       int    newargc    = 0;
 398 
 399       /*
 400        * Starting in 1.5, all unix platforms accept the -d32 and -d64
 401        * options.  On platforms where only one data-model is supported
 402        * (e.g. ia-64 Linux), using the flag for the other data model is
 403        * an error and will terminate the program.
 404        */
 405 
 406       { /* open new scope to declare local variables */
 407         int i;
 408 
 409         newargv = (char **)JLI_MemAlloc((argc+1) * sizeof(char*));
 410         newargv[newargc++] = argv[0];
 411 
 412         /* scan for data model arguments and remove from argument list;
 413            last occurrence determines desired data model */
 414         for (i=1; i < argc; i++) {
 415 
 416           if (JLI_StrCmp(argv[i], "-J-d64") == 0 || JLI_StrCmp(argv[i], "-d64") == 0) {
 417             wanted = 64;
 418             continue;
 419           }
 420           if (JLI_StrCmp(argv[i], "-J-d32") == 0 || JLI_StrCmp(argv[i], "-d32") == 0) {
 421             wanted = 32;
 422             continue;
 423           }
 424           newargv[newargc++] = argv[i];
 425 
 426           if (IsJavaArgs()) {
 427             if (argv[i][0] != '-') continue;
 428           } else {
 429             if (JLI_StrCmp(argv[i], "-classpath") == 0 || JLI_StrCmp(argv[i], "-cp") == 0) {
 430               i++;
 431               if (i >= argc) break;
 432               newargv[newargc++] = argv[i];
 433               continue;
 434             }
 435             if (argv[i][0] != '-') { i++; break; }
 436           }
 437         }
 438 
 439         /* copy rest of args [i .. argc) */
 440         while (i < argc) {
 441           newargv[newargc++] = argv[i++];
 442         }
 443         newargv[newargc] = NULL;
 444 
 445         /*
 446          * newargv has all proper arguments here
 447          */
 448 
 449         argc = newargc;
 450         argv = newargv;
 451       }
 452 
 453       /* If the data model is not changing, it is an error if the
 454          jvmpath does not exist */
 455       if (wanted == running) {
 456         /* Find out where the JRE is that we will be using. */
 457         if (!GetJREPath(jrepath, so_jrepath, arch, JNI_FALSE) ) {
 458           JLI_ReportErrorMessage(JRE_ERROR1);
 459           exit(2);
 460         }
 461         JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%s%s%sjvm.cfg",
 462           jrepath, FILESEP, FILESEP,  "", "");
 463         /* Find the specified JVM type */
 464         if (ReadKnownVMs(jvmcfg, JNI_FALSE) < 1) {
 465           JLI_ReportErrorMessage(CFG_ERROR7);
 466           exit(1);
 467         }
 468 
 469         jvmpath[0] = '\0';
 470         jvmtype = CheckJvmType(pargc, pargv, JNI_FALSE);
 471         if (JLI_StrCmp(jvmtype, "ERROR") == 0) {
 472             JLI_ReportErrorMessage(CFG_ERROR9);
 473             exit(4);
 474         }
 475 
 476         if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, arch, wanted)) {
 477           JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath);
 478           exit(4);
 479         }
 480 
 481         /*
 482          * Mac OS X requires the Cocoa event loop to be run on the "main"
 483          * thread. Spawn off a new thread to run main() and pass
 484          * this thread off to the Cocoa event loop.
 485          */
 486         MacOSXStartup(argc, argv);
 487 
 488         /*
 489          * we seem to have everything we need, so without further ado
 490          * we return back, otherwise proceed to set the environment.
 491          */
 492         return;
 493       } else {  /* do the same speculatively or exit */
 494 #if defined(DUAL_MODE)
 495         if (running != wanted) {
 496           /* Find out where the JRE is that we will be using. */
 497           if (!GetJREPath(jrepath, so_jrepath, GetArchPath(wanted), JNI_TRUE)) {
 498             /* give up and let other code report error message */
 499             JLI_ReportErrorMessage(JRE_ERROR2, wanted);
 500             exit(1);
 501           }
 502           JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%s%s%sjvm.cfg",
 503             jrepath, FILESEP, FILESEP,  "", "");
 504           /*
 505            * Read in jvm.cfg for target data model and process vm
 506            * selection options.
 507            */
 508           if (ReadKnownVMs(jvmcfg, JNI_TRUE) < 1) {
 509             /* give up and let other code report error message */
 510             JLI_ReportErrorMessage(JRE_ERROR2, wanted);
 511             exit(1);
 512           }
 513           jvmpath[0] = '\0';
 514           jvmtype = CheckJvmType(pargc, pargv, JNI_TRUE);
 515           if (JLI_StrCmp(jvmtype, "ERROR") == 0) {
 516             JLI_ReportErrorMessage(CFG_ERROR9);
 517             exit(4);
 518           }
 519 
 520           /* exec child can do error checking on the existence of the path */
 521           jvmpathExists = GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, GetArchPath(wanted), wanted);
 522         }
 523 #else /* ! DUAL_MODE */
 524         JLI_ReportErrorMessage(JRE_ERROR2, wanted);
 525         exit(1);
 526 #endif /* DUAL_MODE */
 527         }
 528         {
 529             char *newexec = execname;
 530             JLI_TraceLauncher("TRACER_MARKER:About to EXEC\n");
 531             (void) fflush(stdout);
 532             (void) fflush(stderr);
 533             /*
 534             * Use posix_spawn() instead of execv() on Mac OS X.
 535             * This allows us to choose which architecture the child process
 536             * should run as.
 537             */
 538             {
 539                 posix_spawnattr_t attr;
 540                 size_t unused_size;
 541                 pid_t  unused_pid;
 542 
 543 #if defined(__i386__) || defined(__x86_64__)
 544                 cpu_type_t cpu_type[] = { (wanted == 64) ? CPU_TYPE_X86_64 : CPU_TYPE_X86,
 545                                     (running== 64) ? CPU_TYPE_X86_64 : CPU_TYPE_X86 };
 546 #else
 547                 cpu_type_t cpu_type[] = { CPU_TYPE_ANY };
 548 #endif /* __i386 .. */
 549 
 550                 posix_spawnattr_init(&attr);
 551                 posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETEXEC);
 552                 posix_spawnattr_setbinpref_np(&attr, sizeof(cpu_type) / sizeof(cpu_type_t),
 553                                             cpu_type, &unused_size);
 554 
 555                 posix_spawn(&unused_pid, newexec, NULL, &attr, argv, environ);
 556             }
 557             JLI_ReportErrorMessageSys(JRE_ERROR4, newexec);
 558 
 559 #if defined(DUAL_MODE)
 560             if (running != wanted) {
 561                 JLI_ReportErrorMessage(JRE_ERROR5, wanted, running);
 562             }
 563 #endif /* DUAL_MODE */
 564         }
 565         exit(1);
 566     }
 567 }
 568 
 569 /*
 570  * VM choosing is done by the launcher (java.c).
 571  */
 572 static jboolean
 573 GetJVMPath(const char *jrepath, const char *jvmtype,
 574            char *jvmpath, jint jvmpathsize, const char * arch, int bitsWanted)
 575 {
 576     struct stat s;
 577 
 578     if (JLI_StrChr(jvmtype, '/')) {
 579         JLI_Snprintf(jvmpath, jvmpathsize, "%s/" JVM_DLL, jvmtype);
 580     } else {
 581         /*
 582          * macosx client library is built thin, i386 only.
 583          * 64 bit client requests must load server library
 584          */
 585         const char *jvmtypeUsed = ((bitsWanted == 64) && (strcmp(jvmtype, "client") == 0)) ? "server" : jvmtype;
 586         JLI_Snprintf(jvmpath, jvmpathsize, "%s/lib/%s/" JVM_DLL, jrepath, jvmtypeUsed);
 587     }
 588 
 589     JLI_TraceLauncher("Does `%s' exist ... ", jvmpath);
 590 
 591     if (stat(jvmpath, &s) == 0) {
 592         JLI_TraceLauncher("yes.\n");
 593         return JNI_TRUE;
 594     } else {
 595         JLI_TraceLauncher("no.\n");
 596         return JNI_FALSE;
 597     }
 598 }
 599 
 600 /*
 601  * Find path to JRE based on .exe's location or registry settings.
 602  */
 603 static jboolean
 604 GetJREPath(char *path, jint pathsize, const char * arch, jboolean speculative)
 605 {
 606     char libjava[MAXPATHLEN];
 607 
 608     if (GetApplicationHome(path, pathsize)) {
 609         /* Is JRE co-located with the application? */
 610         JLI_Snprintf(libjava, sizeof(libjava), "%s/lib/" JAVA_DLL, path);
 611         if (access(libjava, F_OK) == 0) {
 612             return JNI_TRUE;
 613         }
 614         /* ensure storage for path + /jre + NULL */
 615         if ((JLI_StrLen(path) + 4 + 1) > (size_t) pathsize) {
 616             JLI_TraceLauncher("Insufficient space to store JRE path\n");
 617             return JNI_FALSE;
 618         }
 619         /* Does the app ship a private JRE in <apphome>/jre directory? */
 620         JLI_Snprintf(libjava, sizeof(libjava), "%s/jre/lib/" JAVA_DLL, path);
 621         if (access(libjava, F_OK) == 0) {
 622             JLI_StrCat(path, "/jre");
 623             JLI_TraceLauncher("JRE path is %s\n", path);
 624             return JNI_TRUE;
 625         }
 626     }
 627 
 628     /* try to find ourselves instead */
 629     Dl_info selfInfo;
 630     dladdr(&GetJREPath, &selfInfo);
 631 
 632     char *realPathToSelf = realpath(selfInfo.dli_fname, path);
 633     if (realPathToSelf != path) {
 634         return JNI_FALSE;
 635     }
 636 
 637     size_t pathLen = strlen(realPathToSelf);
 638     if (pathLen == 0) {
 639         return JNI_FALSE;
 640     }
 641 
 642     const char lastPathComponent[] = "/lib/jli/libjli.dylib";
 643     size_t sizeOfLastPathComponent = sizeof(lastPathComponent) - 1;
 644     if (pathLen < sizeOfLastPathComponent) {
 645         return JNI_FALSE;
 646     }
 647 
 648     size_t indexOfLastPathComponent = pathLen - sizeOfLastPathComponent;
 649     if (0 == strncmp(realPathToSelf + indexOfLastPathComponent, lastPathComponent, sizeOfLastPathComponent - 1)) {
 650         realPathToSelf[indexOfLastPathComponent + 1] = '\0';
 651         return JNI_TRUE;
 652     }
 653 
 654     if (!speculative)
 655       JLI_ReportErrorMessage(JRE_ERROR8 JAVA_DLL);
 656     return JNI_FALSE;
 657 }
 658 
 659 jboolean
 660 LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)
 661 {
 662     Dl_info dlinfo;
 663     void *libjvm;
 664 
 665     JLI_TraceLauncher("JVM path is %s\n", jvmpath);
 666 
 667     libjvm = dlopen(jvmpath, RTLD_NOW + RTLD_GLOBAL);
 668     if (libjvm == NULL) {
 669         JLI_ReportErrorMessage(DLL_ERROR1, __LINE__);
 670         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
 671         return JNI_FALSE;
 672     }
 673 
 674     ifn->CreateJavaVM = (CreateJavaVM_t)
 675         dlsym(libjvm, "JNI_CreateJavaVM");
 676     if (ifn->CreateJavaVM == NULL) {
 677         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
 678         return JNI_FALSE;
 679     }
 680 
 681     ifn->GetDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs_t)
 682         dlsym(libjvm, "JNI_GetDefaultJavaVMInitArgs");
 683     if (ifn->GetDefaultJavaVMInitArgs == NULL) {
 684         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
 685         return JNI_FALSE;
 686     }
 687 
 688     ifn->GetCreatedJavaVMs = (GetCreatedJavaVMs_t)
 689     dlsym(libjvm, "JNI_GetCreatedJavaVMs");
 690     if (ifn->GetCreatedJavaVMs == NULL) {
 691         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
 692         return JNI_FALSE;
 693     }
 694 
 695     return JNI_TRUE;
 696 }
 697 
 698 /*
 699  * Compute the name of the executable
 700  *
 701  * In order to re-exec securely we need the absolute path of the
 702  * executable. On Solaris getexecname(3c) may not return an absolute
 703  * path so we use dladdr to get the filename of the executable and
 704  * then use realpath to derive an absolute path. From Solaris 9
 705  * onwards the filename returned in DL_info structure from dladdr is
 706  * an absolute pathname so technically realpath isn't required.
 707  * On Linux we read the executable name from /proc/self/exe.
 708  * As a fallback, and for platforms other than Solaris and Linux,
 709  * we use FindExecName to compute the executable name.
 710  */
 711 const char*
 712 SetExecname(char **argv)
 713 {
 714     char* exec_path = NULL;
 715     {
 716         Dl_info dlinfo;
 717         int (*fptr)();
 718 
 719         fptr = (int (*)())dlsym(RTLD_DEFAULT, "main");
 720         if (fptr == NULL) {
 721             JLI_ReportErrorMessage(DLL_ERROR3, dlerror());
 722             return JNI_FALSE;
 723         }
 724 
 725         if (dladdr((void*)fptr, &dlinfo)) {
 726             char *resolved = (char*)JLI_MemAlloc(PATH_MAX+1);
 727             if (resolved != NULL) {
 728                 exec_path = realpath(dlinfo.dli_fname, resolved);
 729                 if (exec_path == NULL) {
 730                     JLI_MemFree(resolved);
 731                 }
 732             }
 733         }
 734     }
 735     if (exec_path == NULL) {
 736         exec_path = FindExecName(argv[0]);
 737     }
 738     execname = exec_path;
 739     return exec_path;
 740 }
 741 
 742 /*
 743  * BSD's implementation of CounterGet()
 744  */
 745 int64_t
 746 CounterGet()
 747 {
 748     struct timeval tv;
 749     gettimeofday(&tv, NULL);
 750     return (tv.tv_sec * 1000) + tv.tv_usec;
 751 }
 752 
 753 
 754 /* --- Splash Screen shared library support --- */
 755 
 756 static JavaVM* SetJavaVMValue()
 757 {
 758     JavaVM * jvm = NULL;
 759 
 760     // The handle is good for both the launcher and the libosxapp.dylib
 761     void * handle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
 762     if (handle) {
 763         typedef JavaVM* (*JLI_GetJavaVMInstance_t)();
 764 
 765         JLI_GetJavaVMInstance_t JLI_GetJavaVMInstance =
 766             (JLI_GetJavaVMInstance_t)dlsym(handle,
 767                     "JLI_GetJavaVMInstance");
 768         if (JLI_GetJavaVMInstance) {
 769             jvm = JLI_GetJavaVMInstance();
 770         }
 771 
 772         if (jvm) {
 773             typedef void (*OSXAPP_SetJavaVM_t)(JavaVM*);
 774 
 775             OSXAPP_SetJavaVM_t OSXAPP_SetJavaVM =
 776                 (OSXAPP_SetJavaVM_t)dlsym(handle, "OSXAPP_SetJavaVM");
 777             if (OSXAPP_SetJavaVM) {
 778                 OSXAPP_SetJavaVM(jvm);
 779             } else {
 780                 jvm = NULL;
 781             }
 782         }
 783 
 784         dlclose(handle);
 785     }
 786 
 787     return jvm;
 788 }
 789 
 790 static const char* SPLASHSCREEN_SO = JNI_LIB_NAME("splashscreen");
 791 
 792 static void* hSplashLib = NULL;
 793 
 794 void* SplashProcAddress(const char* name) {
 795     if (!hSplashLib) {
 796         char jrePath[PATH_MAX];
 797         if (!GetJREPath(jrePath, sizeof(jrePath), GetArch(), JNI_FALSE)) {
 798             JLI_ReportErrorMessage(JRE_ERROR1);
 799             return NULL;
 800         }
 801 
 802         char splashPath[PATH_MAX];
 803         const int ret = JLI_Snprintf(splashPath, sizeof(splashPath),
 804                 "%s/lib/%s", jrePath, SPLASHSCREEN_SO);
 805         if (ret >= (int)sizeof(splashPath)) {
 806             JLI_ReportErrorMessage(JRE_ERROR11);
 807             return NULL;
 808         }
 809         if (ret < 0) {
 810             JLI_ReportErrorMessage(JRE_ERROR13);
 811             return NULL;
 812         }
 813 
 814         hSplashLib = dlopen(splashPath, RTLD_LAZY | RTLD_GLOBAL);
 815         // It's OK if dlopen() fails. The splash screen library binary file
 816         // might have been stripped out from the JRE image to reduce its size
 817         // (e.g. on embedded platforms).
 818 
 819         if (hSplashLib) {
 820             if (!SetJavaVMValue()) {
 821                 dlclose(hSplashLib);
 822                 hSplashLib = NULL;
 823             }
 824         }
 825     }
 826     if (hSplashLib) {
 827         void* sym = dlsym(hSplashLib, name);
 828         return sym;
 829     } else {
 830         return NULL;
 831     }
 832 }
 833 
 834 void SplashFreeLibrary() {
 835     if (hSplashLib) {
 836         dlclose(hSplashLib);
 837         hSplashLib = NULL;
 838     }
 839 }
 840 
 841 /*
 842  * Block current thread and continue execution in a new thread
 843  */
 844 int
 845 ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void * args) {
 846     int rslt;
 847     pthread_t tid;
 848     pthread_attr_t attr;
 849     pthread_attr_init(&attr);
 850     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
 851 
 852     if (stack_size > 0) {
 853       pthread_attr_setstacksize(&attr, stack_size);
 854     }
 855 
 856     if (pthread_create(&tid, &attr, (void *(*)(void*))continuation, (void*)args) == 0) {
 857       void * tmp;
 858       pthread_join(tid, &tmp);
 859       rslt = (int)(intptr_t)tmp;
 860     } else {
 861      /*
 862       * Continue execution in current thread if for some reason (e.g. out of
 863       * memory/LWP)  a new thread can't be created. This will likely fail
 864       * later in continuation as JNI_CreateJavaVM needs to create quite a
 865       * few new threads, anyway, just give it a try..
 866       */
 867       rslt = continuation(args);
 868     }
 869 
 870     pthread_attr_destroy(&attr);
 871     return rslt;
 872 }
 873 
 874 void SetJavaLauncherPlatformProps() {
 875    /* Linux only */
 876 }
 877 
 878 jboolean
 879 ServerClassMachine(void) {
 880     return JNI_TRUE;
 881 }
 882 
 883 static JavaVM* jvmInstance = NULL;
 884 static jboolean sameThread = JNI_FALSE; /* start VM in current thread */
 885 
 886 /*
 887  * Note there is a callback on this function from the splashscreen logic,
 888  * this as well SetJavaVMValue() needs to be simplified.
 889  */
 890 JavaVM*
 891 JLI_GetJavaVMInstance()
 892 {
 893     return jvmInstance;
 894 }
 895 
 896 void
 897 RegisterThread()
 898 {
 899     objc_registerThreadWithCollector();
 900 }
 901 
 902 static void
 903 SetXDockArgForAWT(const char *arg)
 904 {
 905     char envVar[80];
 906     if (strstr(arg, "-Xdock:name=") == arg) {
 907         /*
 908          * The APP_NAME_<pid> environment variable is used to pass
 909          * an application name as specified with the -Xdock:name command
 910          * line option from Java launcher code to the AWT code in order
 911          * to assign this name to the app's dock tile on the Mac.
 912          * The _<pid> part is added to avoid collisions with child processes.
 913          *
 914          * WARNING: This environment variable is an implementation detail and
 915          * isn't meant for use outside of the core platform. The mechanism for
 916          * passing this information from Java launcher to other modules may
 917          * change drastically between update release, and it may even be
 918          * removed or replaced with another mechanism.
 919          *
 920          * NOTE: It is used by SWT, and JavaFX.
 921          */
 922         snprintf(envVar, sizeof(envVar), "APP_NAME_%d", getpid());
 923         setenv(envVar, (arg + 12), 1);
 924     }
 925 
 926     if (strstr(arg, "-Xdock:icon=") == arg) {
 927         /*
 928          * The APP_ICON_<pid> environment variable is used to pass
 929          * an application icon as specified with the -Xdock:icon command
 930          * line option from Java launcher code to the AWT code in order
 931          * to assign this icon to the app's dock tile on the Mac.
 932          * The _<pid> part is added to avoid collisions with child processes.
 933          *
 934          * WARNING: This environment variable is an implementation detail and
 935          * isn't meant for use outside of the core platform. The mechanism for
 936          * passing this information from Java launcher to other modules may
 937          * change drastically between update release, and it may even be
 938          * removed or replaced with another mechanism.
 939          *
 940          * NOTE: It is used by SWT, and JavaFX.
 941          */
 942         snprintf(envVar, sizeof(envVar), "APP_ICON_%d", getpid());
 943         setenv(envVar, (arg + 12), 1);
 944     }
 945 }
 946 
 947 static void
 948 SetMainClassForAWT(JNIEnv *env, jclass mainClass) {
 949     jclass classClass = NULL;
 950     NULL_CHECK(classClass = FindBootStrapClass(env, "java/lang/Class"));
 951 
 952     jmethodID getCanonicalNameMID = NULL;
 953     NULL_CHECK(getCanonicalNameMID = (*env)->GetMethodID(env, classClass, "getCanonicalName", "()Ljava/lang/String;"));
 954 
 955     jstring mainClassString = (*env)->CallObjectMethod(env, mainClass, getCanonicalNameMID);
 956     if ((*env)->ExceptionCheck(env)) {
 957         /*
 958          * Clears all errors caused by getCanonicalName() on the mainclass and
 959          * leaves the JAVA_MAIN_CLASS__<pid> empty.
 960          */
 961         (*env)->ExceptionClear(env);
 962         return;
 963     }
 964 
 965     const char *mainClassName = NULL;
 966     NULL_CHECK(mainClassName = (*env)->GetStringUTFChars(env, mainClassString, NULL));
 967 
 968     char envVar[80];
 969     /*
 970      * The JAVA_MAIN_CLASS_<pid> environment variable is used to pass
 971      * the name of a Java class whose main() method is invoked by
 972      * the Java launcher code to start the application, to the AWT code
 973      * in order to assign the name to the Apple menu bar when the app
 974      * is active on the Mac.
 975      * The _<pid> part is added to avoid collisions with child processes.
 976      *
 977      * WARNING: This environment variable is an implementation detail and
 978      * isn't meant for use outside of the core platform. The mechanism for
 979      * passing this information from Java launcher to other modules may
 980      * change drastically between update release, and it may even be
 981      * removed or replaced with another mechanism.
 982      *
 983      * NOTE: It is used by SWT, and JavaFX.
 984      */
 985     snprintf(envVar, sizeof(envVar), "JAVA_MAIN_CLASS_%d", getpid());
 986     setenv(envVar, mainClassName, 1);
 987 
 988     (*env)->ReleaseStringUTFChars(env, mainClassString, mainClassName);
 989 }
 990 
 991 void
 992 SetXStartOnFirstThreadArg()
 993 {
 994     // XXX: BEGIN HACK
 995     // short circuit hack for <https://bugs.eclipse.org/bugs/show_bug.cgi?id=211625>
 996     // need a way to get AWT/Swing apps launched when spawned from Eclipse,
 997     // which currently has no UI to not pass the -XstartOnFirstThread option
 998     if (getenv("HACK_IGNORE_START_ON_FIRST_THREAD") != NULL) return;
 999     // XXX: END HACK
1000 
1001     sameThread = JNI_TRUE;
1002     // Set a variable that tells us we started on the main thread.
1003     // This is used by the AWT during startup. (See LWCToolkit.m)
1004     char envVar[80];
1005     snprintf(envVar, sizeof(envVar), "JAVA_STARTED_ON_FIRST_THREAD_%d", getpid());
1006     setenv(envVar, "1", 1);
1007 }
1008 
1009 /* This class is made for performSelectorOnMainThread when java main
1010  * should be launched on main thread.
1011  * We cannot use dispatch_sync here, because it blocks the main dispatch queue
1012  * which is used inside Cocoa
1013  */
1014 @interface JavaLaunchHelper : NSObject {
1015     int _returnValue;
1016 }
1017 - (void) launchJava:(NSValue*)argsValue;
1018 - (int) getReturnValue;
1019 @end
1020 
1021 @implementation JavaLaunchHelper
1022 
1023 - (void) launchJava:(NSValue*)argsValue
1024 {
1025     _returnValue = JavaMain([argsValue pointerValue]);
1026 }
1027 
1028 - (int) getReturnValue
1029 {
1030     return _returnValue;
1031 }
1032 
1033 @end
1034 
1035 // MacOSX we may continue in the same thread
1036 int
1037 JVMInit(InvocationFunctions* ifn, jlong threadStackSize,
1038                  int argc, char **argv,
1039                  int mode, char *what, int ret) {
1040     if (sameThread) {
1041         JLI_TraceLauncher("In same thread\n");
1042         // need to block this thread against the main thread
1043         // so signals get caught correctly
1044         JavaMainArgs args;
1045         args.argc = argc;
1046         args.argv = argv;
1047         args.mode = mode;
1048         args.what = what;
1049         args.ifn  = *ifn;
1050         int rslt;
1051         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1052         {
1053             JavaLaunchHelper* launcher = [[[JavaLaunchHelper alloc] init] autorelease];
1054             [launcher performSelectorOnMainThread:@selector(launchJava:)
1055                                        withObject:[NSValue valueWithPointer:(void*)&args]
1056                                     waitUntilDone:YES];
1057             rslt = [launcher getReturnValue];
1058         }
1059         [pool drain];
1060         return rslt;
1061     } else {
1062         return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret);
1063     }
1064 }
1065 
1066 /*
1067  * Note the jvmInstance must be initialized first before entering into
1068  * ShowSplashScreen, as there is a callback into the JLI_GetJavaVMInstance.
1069  */
1070 void PostJVMInit(JNIEnv *env, jclass mainClass, JavaVM *vm) {
1071     jvmInstance = vm;
1072     SetMainClassForAWT(env, mainClass);
1073     CHECK_EXCEPTION_RETURN();
1074     ShowSplashScreen();
1075 }
1076 
1077 jboolean
1078 ProcessPlatformOption(const char* arg)
1079 {
1080     if (JLI_StrCmp(arg, "-XstartOnFirstThread") == 0) {
1081        SetXStartOnFirstThreadArg();
1082        return JNI_TRUE;
1083     } else if (JLI_StrCCmp(arg, "-Xdock:") == 0) {
1084        SetXDockArgForAWT(arg);
1085        return JNI_TRUE;
1086     }
1087     // arguments we know not
1088     return JNI_FALSE;
1089 }