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 
 615         /* Does the app ship a private JRE in <apphome>/jre directory? */
 616         JLI_Snprintf(libjava, sizeof(libjava), "%s/jre/lib/" JAVA_DLL, path);
 617         if (access(libjava, F_OK) == 0) {
 618             JLI_StrCat(path, "/jre");
 619             JLI_TraceLauncher("JRE path is %s\n", path);
 620             return JNI_TRUE;
 621         }
 622     }
 623 
 624     /* try to find ourselves instead */
 625     Dl_info selfInfo;
 626     dladdr(&GetJREPath, &selfInfo);
 627 
 628     char *realPathToSelf = realpath(selfInfo.dli_fname, path);
 629     if (realPathToSelf != path) {
 630         return JNI_FALSE;
 631     }
 632 
 633     size_t pathLen = strlen(realPathToSelf);
 634     if (pathLen == 0) {
 635         return JNI_FALSE;
 636     }
 637 
 638     const char lastPathComponent[] = "/lib/jli/libjli.dylib";
 639     size_t sizeOfLastPathComponent = sizeof(lastPathComponent) - 1;
 640     if (pathLen < sizeOfLastPathComponent) {
 641         return JNI_FALSE;
 642     }
 643 
 644     size_t indexOfLastPathComponent = pathLen - sizeOfLastPathComponent;
 645     if (0 == strncmp(realPathToSelf + indexOfLastPathComponent, lastPathComponent, sizeOfLastPathComponent - 1)) {
 646         realPathToSelf[indexOfLastPathComponent + 1] = '\0';
 647         return JNI_TRUE;
 648     }
 649 
 650     if (!speculative)
 651       JLI_ReportErrorMessage(JRE_ERROR8 JAVA_DLL);
 652     return JNI_FALSE;
 653 }
 654 
 655 jboolean
 656 LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)
 657 {
 658     Dl_info dlinfo;
 659     void *libjvm;
 660 
 661     JLI_TraceLauncher("JVM path is %s\n", jvmpath);
 662 
 663     libjvm = dlopen(jvmpath, RTLD_NOW + RTLD_GLOBAL);
 664     if (libjvm == NULL) {
 665         JLI_ReportErrorMessage(DLL_ERROR1, __LINE__);
 666         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
 667         return JNI_FALSE;
 668     }
 669 
 670     ifn->CreateJavaVM = (CreateJavaVM_t)
 671         dlsym(libjvm, "JNI_CreateJavaVM");
 672     if (ifn->CreateJavaVM == NULL) {
 673         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
 674         return JNI_FALSE;
 675     }
 676 
 677     ifn->GetDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs_t)
 678         dlsym(libjvm, "JNI_GetDefaultJavaVMInitArgs");
 679     if (ifn->GetDefaultJavaVMInitArgs == NULL) {
 680         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
 681         return JNI_FALSE;
 682     }
 683 
 684     ifn->GetCreatedJavaVMs = (GetCreatedJavaVMs_t)
 685     dlsym(libjvm, "JNI_GetCreatedJavaVMs");
 686     if (ifn->GetCreatedJavaVMs == NULL) {
 687         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
 688         return JNI_FALSE;
 689     }
 690 
 691     return JNI_TRUE;
 692 }
 693 
 694 /*
 695  * Compute the name of the executable
 696  *
 697  * In order to re-exec securely we need the absolute path of the
 698  * executable. On Solaris getexecname(3c) may not return an absolute
 699  * path so we use dladdr to get the filename of the executable and
 700  * then use realpath to derive an absolute path. From Solaris 9
 701  * onwards the filename returned in DL_info structure from dladdr is
 702  * an absolute pathname so technically realpath isn't required.
 703  * On Linux we read the executable name from /proc/self/exe.
 704  * As a fallback, and for platforms other than Solaris and Linux,
 705  * we use FindExecName to compute the executable name.
 706  */
 707 const char*
 708 SetExecname(char **argv)
 709 {
 710     char* exec_path = NULL;
 711     {
 712         Dl_info dlinfo;
 713         int (*fptr)();
 714 
 715         fptr = (int (*)())dlsym(RTLD_DEFAULT, "main");
 716         if (fptr == NULL) {
 717             JLI_ReportErrorMessage(DLL_ERROR3, dlerror());
 718             return JNI_FALSE;
 719         }
 720 
 721         if (dladdr((void*)fptr, &dlinfo)) {
 722             char *resolved = (char*)JLI_MemAlloc(PATH_MAX+1);
 723             if (resolved != NULL) {
 724                 exec_path = realpath(dlinfo.dli_fname, resolved);
 725                 if (exec_path == NULL) {
 726                     JLI_MemFree(resolved);
 727                 }
 728             }
 729         }
 730     }
 731     if (exec_path == NULL) {
 732         exec_path = FindExecName(argv[0]);
 733     }
 734     execname = exec_path;
 735     return exec_path;
 736 }
 737 
 738 /*
 739  * BSD's implementation of CounterGet()
 740  */
 741 int64_t
 742 CounterGet()
 743 {
 744     struct timeval tv;
 745     gettimeofday(&tv, NULL);
 746     return (tv.tv_sec * 1000) + tv.tv_usec;
 747 }
 748 
 749 
 750 /* --- Splash Screen shared library support --- */
 751 
 752 static JavaVM* SetJavaVMValue()
 753 {
 754     JavaVM * jvm = NULL;
 755 
 756     // The handle is good for both the launcher and the libosxapp.dylib
 757     void * handle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
 758     if (handle) {
 759         typedef JavaVM* (*JLI_GetJavaVMInstance_t)();
 760 
 761         JLI_GetJavaVMInstance_t JLI_GetJavaVMInstance =
 762             (JLI_GetJavaVMInstance_t)dlsym(handle,
 763                     "JLI_GetJavaVMInstance");
 764         if (JLI_GetJavaVMInstance) {
 765             jvm = JLI_GetJavaVMInstance();
 766         }
 767 
 768         if (jvm) {
 769             typedef void (*OSXAPP_SetJavaVM_t)(JavaVM*);
 770 
 771             OSXAPP_SetJavaVM_t OSXAPP_SetJavaVM =
 772                 (OSXAPP_SetJavaVM_t)dlsym(handle, "OSXAPP_SetJavaVM");
 773             if (OSXAPP_SetJavaVM) {
 774                 OSXAPP_SetJavaVM(jvm);
 775             } else {
 776                 jvm = NULL;
 777             }
 778         }
 779 
 780         dlclose(handle);
 781     }
 782 
 783     return jvm;
 784 }
 785 
 786 static const char* SPLASHSCREEN_SO = JNI_LIB_NAME("splashscreen");
 787 
 788 static void* hSplashLib = NULL;
 789 
 790 void* SplashProcAddress(const char* name) {
 791     if (!hSplashLib) {
 792         char jrePath[PATH_MAX];
 793         if (!GetJREPath(jrePath, sizeof(jrePath), GetArch(), JNI_FALSE)) {
 794             JLI_ReportErrorMessage(JRE_ERROR1);
 795             return NULL;
 796         }
 797 
 798         char splashPath[PATH_MAX];
 799         const int ret = JLI_Snprintf(splashPath, sizeof(splashPath),
 800                 "%s/lib/%s", jrePath, SPLASHSCREEN_SO);
 801         if (ret >= (int)sizeof(splashPath)) {
 802             JLI_ReportErrorMessage(JRE_ERROR11);
 803             return NULL;
 804         }
 805         if (ret < 0) {
 806             JLI_ReportErrorMessage(JRE_ERROR13);
 807             return NULL;
 808         }
 809 
 810         hSplashLib = dlopen(splashPath, RTLD_LAZY | RTLD_GLOBAL);
 811         // It's OK if dlopen() fails. The splash screen library binary file
 812         // might have been stripped out from the JRE image to reduce its size
 813         // (e.g. on embedded platforms).
 814 
 815         if (hSplashLib) {
 816             if (!SetJavaVMValue()) {
 817                 dlclose(hSplashLib);
 818                 hSplashLib = NULL;
 819             }
 820         }
 821     }
 822     if (hSplashLib) {
 823         void* sym = dlsym(hSplashLib, name);
 824         return sym;
 825     } else {
 826         return NULL;
 827     }
 828 }
 829 
 830 void SplashFreeLibrary() {
 831     if (hSplashLib) {
 832         dlclose(hSplashLib);
 833         hSplashLib = NULL;
 834     }
 835 }
 836 
 837 /*
 838  * Block current thread and continue execution in a new thread
 839  */
 840 int
 841 ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void * args) {
 842     int rslt;
 843     pthread_t tid;
 844     pthread_attr_t attr;
 845     pthread_attr_init(&attr);
 846     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
 847 
 848     if (stack_size > 0) {
 849       pthread_attr_setstacksize(&attr, stack_size);
 850     }
 851 
 852     if (pthread_create(&tid, &attr, (void *(*)(void*))continuation, (void*)args) == 0) {
 853       void * tmp;
 854       pthread_join(tid, &tmp);
 855       rslt = (int)(intptr_t)tmp;
 856     } else {
 857      /*
 858       * Continue execution in current thread if for some reason (e.g. out of
 859       * memory/LWP)  a new thread can't be created. This will likely fail
 860       * later in continuation as JNI_CreateJavaVM needs to create quite a
 861       * few new threads, anyway, just give it a try..
 862       */
 863       rslt = continuation(args);
 864     }
 865 
 866     pthread_attr_destroy(&attr);
 867     return rslt;
 868 }
 869 
 870 void SetJavaLauncherPlatformProps() {
 871    /* Linux only */
 872 }
 873 
 874 jboolean
 875 ServerClassMachine(void) {
 876     return JNI_TRUE;
 877 }
 878 
 879 static JavaVM* jvmInstance = NULL;
 880 static jboolean sameThread = JNI_FALSE; /* start VM in current thread */
 881 
 882 /*
 883  * Note there is a callback on this function from the splashscreen logic,
 884  * this as well SetJavaVMValue() needs to be simplified.
 885  */
 886 JavaVM*
 887 JLI_GetJavaVMInstance()
 888 {
 889     return jvmInstance;
 890 }
 891 
 892 void
 893 RegisterThread()
 894 {
 895     objc_registerThreadWithCollector();
 896 }
 897 
 898 static void
 899 SetXDockArgForAWT(const char *arg)
 900 {
 901     char envVar[80];
 902     if (strstr(arg, "-Xdock:name=") == arg) {
 903         /*
 904          * The APP_NAME_<pid> environment variable is used to pass
 905          * an application name as specified with the -Xdock:name command
 906          * line option from Java launcher code to the AWT code in order
 907          * to assign this name to the app's dock tile on the Mac.
 908          * The _<pid> part is added to avoid collisions with child processes.
 909          *
 910          * WARNING: This environment variable is an implementation detail and
 911          * isn't meant for use outside of the core platform. The mechanism for
 912          * passing this information from Java launcher to other modules may
 913          * change drastically between update release, and it may even be
 914          * removed or replaced with another mechanism.
 915          *
 916          * NOTE: It is used by SWT, and JavaFX.
 917          */
 918         snprintf(envVar, sizeof(envVar), "APP_NAME_%d", getpid());
 919         setenv(envVar, (arg + 12), 1);
 920     }
 921 
 922     if (strstr(arg, "-Xdock:icon=") == arg) {
 923         /*
 924          * The APP_ICON_<pid> environment variable is used to pass
 925          * an application icon as specified with the -Xdock:icon command
 926          * line option from Java launcher code to the AWT code in order
 927          * to assign this icon to the app's dock tile on the Mac.
 928          * The _<pid> part is added to avoid collisions with child processes.
 929          *
 930          * WARNING: This environment variable is an implementation detail and
 931          * isn't meant for use outside of the core platform. The mechanism for
 932          * passing this information from Java launcher to other modules may
 933          * change drastically between update release, and it may even be
 934          * removed or replaced with another mechanism.
 935          *
 936          * NOTE: It is used by SWT, and JavaFX.
 937          */
 938         snprintf(envVar, sizeof(envVar), "APP_ICON_%d", getpid());
 939         setenv(envVar, (arg + 12), 1);
 940     }
 941 }
 942 
 943 static void
 944 SetMainClassForAWT(JNIEnv *env, jclass mainClass) {
 945     jclass classClass = NULL;
 946     NULL_CHECK(classClass = FindBootStrapClass(env, "java/lang/Class"));
 947 
 948     jmethodID getCanonicalNameMID = NULL;
 949     NULL_CHECK(getCanonicalNameMID = (*env)->GetMethodID(env, classClass, "getCanonicalName", "()Ljava/lang/String;"));
 950 
 951     jstring mainClassString = (*env)->CallObjectMethod(env, mainClass, getCanonicalNameMID);
 952     if ((*env)->ExceptionCheck(env)) {
 953         (*env)->ExceptionClear(env);
 954         return;
 955     }
 956 
 957     const char *mainClassName = NULL;
 958     NULL_CHECK(mainClassName = (*env)->GetStringUTFChars(env, mainClassString, NULL));
 959 
 960     char envVar[80];
 961     /*
 962      * The JAVA_MAIN_CLASS_<pid> environment variable is used to pass
 963      * the name of a Java class whose main() method is invoked by
 964      * the Java launcher code to start the application, to the AWT code
 965      * in order to assign the name to the Apple menu bar when the app
 966      * is active on the Mac.
 967      * The _<pid> part is added to avoid collisions with child processes.
 968      *
 969      * WARNING: This environment variable is an implementation detail and
 970      * isn't meant for use outside of the core platform. The mechanism for
 971      * passing this information from Java launcher to other modules may
 972      * change drastically between update release, and it may even be
 973      * removed or replaced with another mechanism.
 974      *
 975      * NOTE: It is used by SWT, and JavaFX.
 976      */
 977     snprintf(envVar, sizeof(envVar), "JAVA_MAIN_CLASS_%d", getpid());
 978     setenv(envVar, mainClassName, 1);
 979 
 980     (*env)->ReleaseStringUTFChars(env, mainClassString, mainClassName);
 981 }
 982 
 983 void
 984 SetXStartOnFirstThreadArg()
 985 {
 986     // XXX: BEGIN HACK
 987     // short circuit hack for <https://bugs.eclipse.org/bugs/show_bug.cgi?id=211625>
 988     // need a way to get AWT/Swing apps launched when spawned from Eclipse,
 989     // which currently has no UI to not pass the -XstartOnFirstThread option
 990     if (getenv("HACK_IGNORE_START_ON_FIRST_THREAD") != NULL) return;
 991     // XXX: END HACK
 992 
 993     sameThread = JNI_TRUE;
 994     // Set a variable that tells us we started on the main thread.
 995     // This is used by the AWT during startup. (See LWCToolkit.m)
 996     char envVar[80];
 997     snprintf(envVar, sizeof(envVar), "JAVA_STARTED_ON_FIRST_THREAD_%d", getpid());
 998     setenv(envVar, "1", 1);
 999 }
1000 
1001 /* This class is made for performSelectorOnMainThread when java main
1002  * should be launched on main thread.
1003  * We cannot use dispatch_sync here, because it blocks the main dispatch queue
1004  * which is used inside Cocoa
1005  */
1006 @interface JavaLaunchHelper : NSObject {
1007     int _returnValue;
1008 }
1009 - (void) launchJava:(NSValue*)argsValue;
1010 - (int) getReturnValue;
1011 @end
1012 
1013 @implementation JavaLaunchHelper
1014 
1015 - (void) launchJava:(NSValue*)argsValue
1016 {
1017     _returnValue = JavaMain([argsValue pointerValue]);
1018 }
1019 
1020 - (int) getReturnValue
1021 {
1022     return _returnValue;
1023 }
1024 
1025 @end
1026 
1027 // MacOSX we may continue in the same thread
1028 int
1029 JVMInit(InvocationFunctions* ifn, jlong threadStackSize,
1030                  int argc, char **argv,
1031                  int mode, char *what, int ret) {
1032     if (sameThread) {
1033         JLI_TraceLauncher("In same thread\n");
1034         // need to block this thread against the main thread
1035         // so signals get caught correctly
1036         JavaMainArgs args;
1037         args.argc = argc;
1038         args.argv = argv;
1039         args.mode = mode;
1040         args.what = what;
1041         args.ifn  = *ifn;
1042         int rslt;
1043         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1044         {
1045             JavaLaunchHelper* launcher = [[[JavaLaunchHelper alloc] init] autorelease];
1046             [launcher performSelectorOnMainThread:@selector(launchJava:)
1047                                        withObject:[NSValue valueWithPointer:(void*)&args]
1048                                     waitUntilDone:YES];
1049             rslt = [launcher getReturnValue];
1050         }
1051         [pool drain];
1052         return rslt;
1053     } else {
1054         return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret);
1055     }
1056 }
1057 
1058 /*
1059  * Note the jvmInstance must be initialized first before entering into
1060  * ShowSplashScreen, as there is a callback into the JLI_GetJavaVMInstance.
1061  */
1062 void PostJVMInit(JNIEnv *env, jclass mainClass, JavaVM *vm) {
1063     jvmInstance = vm;
1064     SetMainClassForAWT(env, mainClass);
1065     CHECK_EXCEPTION_RETURN();
1066     ShowSplashScreen();
1067 }
1068 
1069 jboolean
1070 ProcessPlatformOption(const char* arg)
1071 {
1072     if (JLI_StrCmp(arg, "-XstartOnFirstThread") == 0) {
1073        SetXStartOnFirstThreadArg();
1074        return JNI_TRUE;
1075     } else if (JLI_StrCCmp(arg, "-Xdock:") == 0) {
1076        SetXDockArgForAWT(arg);
1077        return JNI_TRUE;
1078     }
1079     // arguments we know not
1080     return JNI_FALSE;
1081 }