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