1 /*
   2  * Copyright (c) 1998, 2013, 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 "manifest_info.h"
  39 #include "version_comp.h"
  40 
  41 
  42 #define JVM_DLL "libjvm.so"
  43 #define JAVA_DLL "libjava.so"
  44 #ifdef AIX
  45 #define LD_LIBRARY_PATH "LIBPATH"
  46 #else
  47 #define LD_LIBRARY_PATH "LD_LIBRARY_PATH"
  48 #endif
  49 
  50 /* help jettison the LD_LIBRARY_PATH settings in the future */
  51 #ifndef SETENV_REQUIRED
  52 #define SETENV_REQUIRED
  53 #endif
  54 /*
  55  * If a processor / os combination has the ability to run binaries of
  56  * two data models and cohabitation of jre/jdk bits with both data
  57  * models is supported, then DUAL_MODE is defined.  When DUAL_MODE is
  58  * defined, the architecture names for the narrow and wide version of
  59  * the architecture are defined in LIBARCH64NAME and LIBARCH32NAME.
  60  * Currently  only Solaris on sparc/sparcv9 and i586/amd64 is DUAL_MODE;
  61  * linux i586/amd64 could be defined as DUAL_MODE but that is not the
  62  * current policy.
  63  */
  64 
  65 #ifdef __solaris__
  66 #  ifndef LIBARCH32NAME
  67 #    error "The macro LIBARCH32NAME was not defined on the compile line"
  68 #  endif
  69 #  ifndef LIBARCH64NAME
  70 #    error "The macro LIBARCH64NAME was not defined on the compile line"
  71 #  endif
  72 #  include <sys/systeminfo.h>
  73 #  include <sys/elf.h>
  74 #  include <stdio.h>
  75 #endif
  76 
  77 /*
  78  * Flowchart of launcher execs and options processing on unix
  79  *
  80  * The selection of the proper vm shared library to open depends on
  81  * several classes of command line options, including vm "flavor"
  82  * options (-client, -server) and the data model options, -d32  and
  83  * -d64, as well as a version specification which may have come from
  84  * the command line or from the manifest of an executable jar file.
  85  * The vm selection options are not passed to the running
  86  * virtual machine; they must be screened out by the launcher.
  87  *
  88  * The version specification (if any) is processed first by the
  89  * platform independent routine SelectVersion.  This may result in
  90  * the exec of the specified launcher version.
  91  *
  92  * Previously the launcher modified the LD_LIBRARY_PATH appropriately for the
  93  * desired data model path, regardless if data models matched or not. The
  94  * launcher subsequently exec'ed the desired executable, in order to make the
  95  * LD_LIBRARY_PATH path available, for the runtime linker.
  96  *
  97  * Now, in most cases,the launcher will dlopen the target libjvm.so. All
  98  * required libraries are loaded by the runtime linker, using the
  99  * $RPATH/$ORIGIN baked into the shared libraries at compile time. Therefore,
 100  * in most cases, the launcher will only exec, if the data models are
 101  * mismatched, and will not set any environment variables, regardless of the
 102  * data models.
 103  *
 104  * However, if the environment contains a LD_LIBRARY_PATH, this will cause the
 105  * launcher to inspect the LD_LIBRARY_PATH. The launcher will check
 106  *  a. if the LD_LIBRARY_PATH's first component is the the path to the desired
 107  *     libjvm.so
 108  *  b. if any other libjvm.so is found in any of the paths.
 109  * If case b is true, then the launcher will set the LD_LIBRARY_PATH to the
 110  * desired JRE and reexec, in order to propagate the environment.
 111  *
 112  *  Main
 113  *  (incoming argv)
 114  *  |
 115  * \|/
 116  * SelectVersion
 117  * (selects the JRE version, note: not data model)
 118  *  |
 119  * \|/
 120  * CreateExecutionEnvironment
 121  * (determines desired data model)
 122  *  |
 123  *  |
 124  * \|/
 125  *  Have Desired Model ? --> NO --> Is Dual-Mode ? --> NO --> Exit(with error)
 126  *  |                                          |
 127  *  |                                          |
 128  *  |                                         \|/
 129  *  |                                         YES
 130  *  |                                          |
 131  *  |                                          |
 132  *  |                                         \|/
 133  *  |                                CheckJvmType
 134  *  |                               (removes -client, -server etc.)
 135  *  |                                          |
 136  *  |                                          |
 137  * \|/                                        \|/
 138  * YES                             Find the desired executable/library
 139  *  |                                          |
 140  *  |                                          |
 141  * \|/                                        \|/
 142  * CheckJvmType                          RequiresSetenv
 143  * (removes -client, -server, etc.)
 144  *  |
 145  *  |
 146  * \|/
 147  * TranslateDashJArgs...
 148  * (Prepare to pass args to vm)
 149  *  |
 150  *  |
 151  * \|/
 152  * ParseArguments
 153  * (removes -d32 and -d64 if any,
 154  *  processes version options,
 155  *  creates argument list for vm,
 156  *  etc.)
 157  *   |
 158  *   |
 159  *  \|/
 160  * RequiresSetenv
 161  * Is LD_LIBRARY_PATH
 162  * and friends set ? --> NO --> Have Desired Model ? NO --> Re-exec --> Main
 163  *  YES                              YES --> Continue
 164  *   |
 165  *   |
 166  *  \|/
 167  * Path is desired JRE ? YES --> Have Desired Model ? NO --> Re-exec --> Main
 168  *  NO                               YES --> Continue
 169  *   |
 170  *   |
 171  *  \|/
 172  * Paths have well known
 173  * jvm paths ?       --> NO --> Have Desired Model ? NO --> Re-exec --> Main
 174  *  YES                              YES --> Continue
 175  *   |
 176  *   |
 177  *  \|/
 178  *  Does libjvm.so exit
 179  *  in any of them ? --> NO --> Have Desired Model ? NO --> Re-exec --> Main
 180  *   YES                             YES --> Continue
 181  *   |
 182  *   |
 183  *  \|/
 184  *  Set the LD_LIBRARY_PATH
 185  *   |
 186  *   |
 187  *  \|/
 188  * Re-exec
 189  *   |
 190  *   |
 191  *  \|/
 192  * Main
 193  */
 194 
 195 #define GetArch() GetArchPath(CURRENT_DATA_MODEL)
 196 
 197 /* Store the name of the executable once computed */
 198 static char *execname = NULL;
 199 
 200 /*
 201  * execname accessor from other parts of platform dependent logic
 202  */
 203 const char *
 204 GetExecName() {
 205     return execname;
 206 }
 207 
 208 const char *
 209 GetArchPath(int nbits)
 210 {
 211     switch(nbits) {
 212 #ifdef DUAL_MODE
 213         case 32:
 214             return LIBARCH32NAME;
 215         case 64:
 216             return LIBARCH64NAME;
 217 #endif /* DUAL_MODE */
 218         default:
 219             return LIBARCHNAME;
 220     }
 221 }
 222 
 223 #ifdef SETENV_REQUIRED
 224 static jboolean
 225 JvmExists(const char *path) {
 226     char tmp[PATH_MAX + 1];
 227     struct stat statbuf;
 228     JLI_Snprintf(tmp, PATH_MAX, "%s/%s", path, JVM_DLL);
 229     if (stat(tmp, &statbuf) == 0) {
 230         return JNI_TRUE;
 231     }
 232     return JNI_FALSE;
 233 }
 234 /*
 235  * contains a lib/$LIBARCH/{server,client}/libjvm.so ?
 236  */
 237 static jboolean
 238 ContainsLibJVM(int wanted, const char *env) {
 239     char clientPattern[PATH_MAX + 1];
 240     char serverPattern[PATH_MAX + 1];
 241     char *envpath;
 242     char *path;
 243     jboolean clientPatternFound;
 244     jboolean serverPatternFound;
 245 
 246     /* fastest path */
 247     if (env == NULL) {
 248         return JNI_FALSE;
 249     }
 250 
 251     /* the usual suspects */
 252     JLI_Snprintf(clientPattern, PATH_MAX, "lib/%s/client", GetArchPath(wanted));
 253     JLI_Snprintf(serverPattern, PATH_MAX, "lib/%s/server", GetArchPath(wanted));
 254 
 255     /* to optimize for time, test if any of our usual suspects are present. */
 256     clientPatternFound = JLI_StrStr(env, clientPattern) != NULL;
 257     serverPatternFound = JLI_StrStr(env, serverPattern) != NULL;
 258     if (clientPatternFound == JNI_FALSE && serverPatternFound == JNI_FALSE) {
 259         return JNI_FALSE;
 260     }
 261 
 262     /*
 263      * we have a suspicious path component, check if it contains a libjvm.so
 264      */
 265     envpath = JLI_StringDup(env);
 266     for (path = JLI_StrTok(envpath, ":"); path != NULL; path = JLI_StrTok(NULL, ":")) {
 267         if (clientPatternFound && JLI_StrStr(path, clientPattern) != NULL) {
 268             if (JvmExists(path)) {
 269                 JLI_MemFree(envpath);
 270                 return JNI_TRUE;
 271             }
 272         }
 273         if (serverPatternFound && JLI_StrStr(path, serverPattern)  != NULL) {
 274             if (JvmExists(path)) {
 275                 JLI_MemFree(envpath);
 276                 return JNI_TRUE;
 277             }
 278         }
 279     }
 280     JLI_MemFree(envpath);
 281     return JNI_FALSE;
 282 }
 283 
 284 /*
 285  * Test whether the environment variable needs to be set, see flowchart.
 286  */
 287 static jboolean
 288 RequiresSetenv(int wanted, const char *jvmpath) {
 289     char jpath[PATH_MAX + 1];
 290     char *llp;
 291     char *dmllp = NULL;
 292     char *p; /* a utility pointer */
 293 
 294 #ifdef AIX
 295     /* We always have to set the LIBPATH on AIX because ld doesn't support $ORIGIN. */
 296     return JNI_TRUE;
 297 #endif
 298 
 299     llp = getenv("LD_LIBRARY_PATH");
 300 #ifdef __solaris__
 301     dmllp = (CURRENT_DATA_MODEL == 32)
 302             ? getenv("LD_LIBRARY_PATH_32")
 303             : getenv("LD_LIBRARY_PATH_64");
 304 #endif /* __solaris__ */
 305     /* no environment variable is a good environment variable */
 306     if (llp == NULL && dmllp == NULL) {
 307         return JNI_FALSE;
 308     }
 309 #ifdef __linux
 310     /*
 311      * On linux, if a binary is running as sgid or suid, glibc sets
 312      * LD_LIBRARY_PATH to the empty string for security purposes. (In contrast,
 313      * on Solaris the LD_LIBRARY_PATH variable for a privileged binary does not
 314      * lose its settings; but the dynamic linker does apply more scrutiny to the
 315      * path.) The launcher uses the value of LD_LIBRARY_PATH to prevent an exec
 316      * loop, here and further downstream. Therefore, if we are running sgid or
 317      * suid, this function's setting of LD_LIBRARY_PATH will be ineffective and
 318      * we should case a return from the calling function.  Getting the right
 319      * libraries will be handled by the RPATH. In reality, this check is
 320      * redundant, as the previous check for a non-null LD_LIBRARY_PATH will
 321      * return back to the calling function forthwith, it is left here to safe
 322      * guard against any changes, in the glibc's existing security policy.
 323      */
 324     if ((getgid() != getegid()) || (getuid() != geteuid())) {
 325         return JNI_FALSE;
 326     }
 327 #endif /* __linux */
 328 
 329     /*
 330      * Prevent recursions. Since LD_LIBRARY_PATH is the one which will be set by
 331      * previous versions of the JRE, thus it is the only path that matters here.
 332      * So we check to see if the desired JRE is set.
 333      */
 334     JLI_StrNCpy(jpath, jvmpath, PATH_MAX);
 335     p = JLI_StrRChr(jpath, '/');
 336     *p = '\0';
 337     if (llp != NULL && JLI_StrNCmp(llp, jpath, JLI_StrLen(jpath)) == 0) {
 338         return JNI_FALSE;
 339     }
 340 
 341     /* scrutinize all the paths further */
 342     if (llp != NULL &&  ContainsLibJVM(wanted, llp)) {
 343         return JNI_TRUE;
 344     }
 345     if (dmllp != NULL && ContainsLibJVM(wanted, dmllp)) {
 346         return JNI_TRUE;
 347     }
 348     return JNI_FALSE;
 349 }
 350 #endif /* SETENV_REQUIRED */
 351 
 352 void
 353 CreateExecutionEnvironment(int *pargc, char ***pargv,
 354                            char jrepath[], jint so_jrepath,
 355                            char jvmpath[], jint so_jvmpath,
 356                            char jvmcfg[],  jint so_jvmcfg) {
 357   /*
 358    * First, determine if we are running the desired data model.  If we
 359    * are running the desired data model, all the error messages
 360    * associated with calling GetJREPath, ReadKnownVMs, etc. should be
 361    * output.  However, if we are not running the desired data model,
 362    * some of the errors should be suppressed since it is more
 363    * informative to issue an error message based on whether or not the
 364    * os/processor combination has dual mode capabilities.
 365    */
 366     jboolean jvmpathExists;
 367 
 368     /* Compute/set the name of the executable */
 369     SetExecname(*pargv);
 370 
 371     /* Check data model flags, and exec process, if needed */
 372     {
 373       char *arch        = (char *)GetArch(); /* like sparc or sparcv9 */
 374       char * jvmtype    = NULL;
 375       int  argc         = *pargc;
 376       char **argv       = *pargv;
 377       int running       = CURRENT_DATA_MODEL;
 378 
 379       int wanted        = running;      /* What data mode is being
 380                                            asked for? Current model is
 381                                            fine unless another model
 382                                            is asked for */
 383 #ifdef SETENV_REQUIRED
 384       jboolean mustsetenv = JNI_FALSE;
 385       char *runpath     = NULL; /* existing effective LD_LIBRARY_PATH setting */
 386       char* new_runpath = NULL; /* desired new LD_LIBRARY_PATH string */
 387       char* newpath     = NULL; /* path on new LD_LIBRARY_PATH */
 388       char* lastslash   = NULL;
 389       char** newenvp    = NULL; /* current environment */
 390 #ifdef __solaris__
 391       char*  dmpath     = NULL;  /* data model specific LD_LIBRARY_PATH,
 392                                     Solaris only */
 393 #endif /* __solaris__ */
 394 #endif  /* SETENV_REQUIRED */
 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,  arch, 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, 0 )) {
 477           JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath);
 478           exit(4);
 479         }
 480         /*
 481          * we seem to have everything we need, so without further ado
 482          * we return back, otherwise proceed to set the environment.
 483          */
 484 #ifdef SETENV_REQUIRED
 485         mustsetenv = RequiresSetenv(wanted, jvmpath);
 486         JLI_TraceLauncher("mustsetenv: %s\n", mustsetenv ? "TRUE" : "FALSE");
 487 
 488         if (mustsetenv == JNI_FALSE) {
 489             JLI_MemFree(newargv);
 490             return;
 491         }
 492 #else
 493         JLI_MemFree(newargv);
 494         return;
 495 #endif /* SETENV_REQUIRED */
 496       } else {  /* do the same speculatively or exit */
 497 #ifdef DUAL_MODE
 498         if (running != wanted) {
 499           /* Find out where the JRE is that we will be using. */
 500           if (!GetJREPath(jrepath, so_jrepath, GetArchPath(wanted), JNI_TRUE)) {
 501             /* give up and let other code report error message */
 502             JLI_ReportErrorMessage(JRE_ERROR2, wanted);
 503             exit(1);
 504           }
 505           JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%s%s%sjvm.cfg",
 506                        jrepath, FILESEP, FILESEP, GetArchPath(wanted), FILESEP);
 507           /*
 508            * Read in jvm.cfg for target data model and process vm
 509            * selection options.
 510            */
 511           if (ReadKnownVMs(jvmcfg, JNI_TRUE) < 1) {
 512             /* give up and let other code report error message */
 513             JLI_ReportErrorMessage(JRE_ERROR2, wanted);
 514             exit(1);
 515           }
 516           jvmpath[0] = '\0';
 517           jvmtype = CheckJvmType(pargc, pargv, JNI_TRUE);
 518           if (JLI_StrCmp(jvmtype, "ERROR") == 0) {
 519             JLI_ReportErrorMessage(CFG_ERROR9);
 520             exit(4);
 521           }
 522 
 523           /* exec child can do error checking on the existence of the path */
 524           jvmpathExists = GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, GetArchPath(wanted), 0);
 525 #ifdef SETENV_REQUIRED
 526           mustsetenv = RequiresSetenv(wanted, jvmpath);
 527 #endif /* SETENV_REQUIRED */
 528         }
 529 #else /* ! DUALMODE */
 530         JLI_ReportErrorMessage(JRE_ERROR2, wanted);
 531         exit(1);
 532 #endif /* DUAL_MODE */
 533         }
 534 #ifdef SETENV_REQUIRED
 535         if (mustsetenv) {
 536             /*
 537              * We will set the LD_LIBRARY_PATH as follows:
 538              *
 539              *     o          $JVMPATH (directory portion only)
 540              *     o          $JRE/lib/$LIBARCHNAME
 541              *     o          $JRE/../lib/$LIBARCHNAME
 542              *
 543              * followed by the user's previous effective LD_LIBRARY_PATH, if
 544              * any.
 545              */
 546 
 547 #ifdef __solaris__
 548             /*
 549              * Starting in Solaris 7, ld.so.1 supports three LD_LIBRARY_PATH
 550              * variables:
 551              *
 552              * 1. LD_LIBRARY_PATH -- used for 32 and 64 bit searches if
 553              * data-model specific variables are not set.
 554              *
 555              * 2. LD_LIBRARY_PATH_64 -- overrides and replaces LD_LIBRARY_PATH
 556              * for 64-bit binaries.
 557              *
 558              * 3. LD_LIBRARY_PATH_32 -- overrides and replaces LD_LIBRARY_PATH
 559              * for 32-bit binaries.
 560              *
 561              * The vm uses LD_LIBRARY_PATH to set the java.library.path system
 562              * property.  To shield the vm from the complication of multiple
 563              * LD_LIBRARY_PATH variables, if the appropriate data model
 564              * specific variable is set, we will act as if LD_LIBRARY_PATH had
 565              * the value of the data model specific variant and the data model
 566              * specific variant will be unset.  Note that the variable for the
 567              * *wanted* data model must be used (if it is set), not simply the
 568              * current running data model.
 569              */
 570 
 571             switch (wanted) {
 572                 case 0:
 573                     if (running == 32) {
 574                         dmpath = getenv("LD_LIBRARY_PATH_32");
 575                         wanted = 32;
 576                     } else {
 577                         dmpath = getenv("LD_LIBRARY_PATH_64");
 578                         wanted = 64;
 579                     }
 580                     break;
 581 
 582                 case 32:
 583                     dmpath = getenv("LD_LIBRARY_PATH_32");
 584                     break;
 585 
 586                 case 64:
 587                     dmpath = getenv("LD_LIBRARY_PATH_64");
 588                     break;
 589 
 590                 default:
 591                     JLI_ReportErrorMessage(JRE_ERROR3, __LINE__);
 592                     exit(1); /* unknown value in wanted */
 593                     break;
 594             }
 595 
 596             /*
 597              * If dmpath is NULL, the relevant data model specific variable is
 598              * not set and normal LD_LIBRARY_PATH should be used.
 599              */
 600             if (dmpath == NULL) {
 601                 runpath = getenv("LD_LIBRARY_PATH");
 602             } else {
 603                 runpath = dmpath;
 604             }
 605 #else /* ! __solaris__ */
 606             /*
 607              * If not on Solaris, assume only a single LD_LIBRARY_PATH
 608              * variable.
 609              */
 610             runpath = getenv(LD_LIBRARY_PATH);
 611 #endif /* __solaris__ */
 612 
 613             /* runpath contains current effective LD_LIBRARY_PATH setting */
 614 
 615             jvmpath = JLI_StringDup(jvmpath);
 616             new_runpath = JLI_MemAlloc(((runpath != NULL) ? JLI_StrLen(runpath) : 0) +
 617                     2 * JLI_StrLen(jrepath) + 2 * JLI_StrLen(arch) +
 618 #ifdef AIX
 619                     /* On AIX we additionally need 'jli' in the path because ld doesn't support $ORIGIN. */
 620                     JLI_StrLen(jrepath) + JLI_StrLen(arch) + JLI_StrLen("/lib//jli:") +
 621 #endif
 622                     JLI_StrLen(jvmpath) + 52);
 623             newpath = new_runpath + JLI_StrLen(LD_LIBRARY_PATH "=");
 624 
 625 
 626             /*
 627              * Create desired LD_LIBRARY_PATH value for target data model.
 628              */
 629             {
 630                 /* remove the name of the .so from the JVM path */
 631                 lastslash = JLI_StrRChr(jvmpath, '/');
 632                 if (lastslash)
 633                     *lastslash = '\0';
 634 
 635                 sprintf(new_runpath, LD_LIBRARY_PATH "="
 636                         "%s:"
 637                         "%s/lib/%s:"
 638 #ifdef AIX
 639                         "%s/lib/%s/jli:" /* Needed on AIX because ld doesn't support $ORIGIN. */
 640 #endif
 641                         "%s/../lib/%s",
 642                         jvmpath,
 643 #ifdef DUAL_MODE
 644                         jrepath, GetArchPath(wanted),
 645                         jrepath, GetArchPath(wanted)
 646 #else /* !DUAL_MODE */
 647                         jrepath, arch,
 648 #ifdef AIX
 649                         jrepath, arch,
 650 #endif
 651                         jrepath, arch
 652 #endif /* DUAL_MODE */
 653                         );
 654 
 655 
 656                 /*
 657                  * Check to make sure that the prefix of the current path is the
 658                  * desired environment variable setting, though the RequiresSetenv
 659                  * checks if the desired runpath exists, this logic does a more
 660                  * comprehensive check.
 661                  */
 662                 if (runpath != NULL &&
 663                         JLI_StrNCmp(newpath, runpath, JLI_StrLen(newpath)) == 0 &&
 664                         (runpath[JLI_StrLen(newpath)] == 0 || runpath[JLI_StrLen(newpath)] == ':') &&
 665                         (running == wanted) /* data model does not have to be changed */
 666 #ifdef __solaris__
 667                         && (dmpath == NULL) /* data model specific variables not set  */
 668 #endif /* __solaris__ */
 669                         ) {
 670                     JLI_MemFree(newargv);
 671                     JLI_MemFree(new_runpath);
 672                     return;
 673                 }
 674             }
 675 
 676             /*
 677              * Place the desired environment setting onto the prefix of
 678              * LD_LIBRARY_PATH.  Note that this prevents any possible infinite
 679              * loop of execv() because we test for the prefix, above.
 680              */
 681             if (runpath != 0) {
 682                 JLI_StrCat(new_runpath, ":");
 683                 JLI_StrCat(new_runpath, runpath);
 684             }
 685 
 686             if (putenv(new_runpath) != 0) {
 687                 exit(1); /* problem allocating memory; LD_LIBRARY_PATH not set
 688                     properly */
 689             }
 690 
 691             /*
 692              * Unix systems document that they look at LD_LIBRARY_PATH only
 693              * once at startup, so we have to re-exec the current executable
 694              * to get the changed environment variable to have an effect.
 695              */
 696 
 697 #ifdef __solaris__
 698             /*
 699              * If dmpath is not NULL, remove the data model specific string
 700              * in the environment for the exec'ed child.
 701              */
 702             if (dmpath != NULL)
 703                 (void)UnsetEnv((wanted == 32) ? "LD_LIBRARY_PATH_32" : "LD_LIBRARY_PATH_64");
 704 #endif /* __solaris */
 705 
 706             newenvp = environ;
 707         }
 708 #endif /* SETENV_REQUIRED */
 709         {
 710             char *newexec = execname;
 711 #ifdef DUAL_MODE
 712             /*
 713              * If the data model is being changed, the path to the
 714              * executable must be updated accordingly; the executable name
 715              * and directory the executable resides in are separate.  In the
 716              * case of 32 => 64, the new bits are assumed to reside in, e.g.
 717              * "olddir/LIBARCH64NAME/execname"; in the case of 64 => 32,
 718              * the bits are assumed to be in "olddir/../execname".  For example,
 719              *
 720              * olddir/sparcv9/execname
 721              * olddir/amd64/execname
 722              *
 723              * for Solaris SPARC and Linux amd64, respectively.
 724              */
 725 
 726             if (running != wanted) {
 727                 char *oldexec = JLI_StrCpy(JLI_MemAlloc(JLI_StrLen(execname) + 1), execname);
 728                 char *olddir = oldexec;
 729                 char *oldbase = JLI_StrRChr(oldexec, '/');
 730 
 731 
 732                 newexec = JLI_MemAlloc(JLI_StrLen(execname) + 20);
 733                 *oldbase++ = 0;
 734                 sprintf(newexec, "%s/%s/%s", olddir,
 735                         ((wanted == 64) ? LIBARCH64NAME : ".."), oldbase);
 736                 argv[0] = newexec;
 737             }
 738 #endif /* DUAL_MODE */
 739             JLI_TraceLauncher("TRACER_MARKER:About to EXEC\n");
 740             (void) fflush(stdout);
 741             (void) fflush(stderr);
 742 #ifdef SETENV_REQUIRED
 743             if (mustsetenv) {
 744                 execve(newexec, argv, newenvp);
 745             } else {
 746                 execv(newexec, argv);
 747             }
 748 #else /* !SETENV_REQUIRED */
 749             execv(newexec, argv);
 750 #endif /* SETENV_REQUIRED */
 751             JLI_ReportErrorMessageSys(JRE_ERROR4, newexec);
 752 
 753 #ifdef DUAL_MODE
 754             if (running != wanted) {
 755                 JLI_ReportErrorMessage(JRE_ERROR5, wanted, running);
 756 #ifdef __solaris__
 757 #ifdef __sparc
 758                 JLI_ReportErrorMessage(JRE_ERROR6);
 759 #else  /* ! __sparc__ */
 760                 JLI_ReportErrorMessage(JRE_ERROR7);
 761 #endif  /* __sparc */
 762 #endif /* __solaris__ */
 763             }
 764 #endif /* DUAL_MODE */
 765 
 766         }
 767         exit(1);
 768     }
 769 }
 770 
 771 /*
 772  * On Solaris VM choosing is done by the launcher (java.c),
 773  * bitsWanted is used by MacOSX,  on Solaris and Linux this.
 774  * parameter is unused.
 775  */
 776 static jboolean
 777 GetJVMPath(const char *jrepath, const char *jvmtype,
 778            char *jvmpath, jint jvmpathsize, const char * arch, int bitsWanted)
 779 {
 780     struct stat s;
 781 
 782     if (JLI_StrChr(jvmtype, '/')) {
 783         JLI_Snprintf(jvmpath, jvmpathsize, "%s/" JVM_DLL, jvmtype);
 784     } else {
 785         JLI_Snprintf(jvmpath, jvmpathsize, "%s/lib/%s/%s/" JVM_DLL, jrepath, arch, jvmtype);
 786     }
 787 
 788     JLI_TraceLauncher("Does `%s' exist ... ", jvmpath);
 789 
 790     if (stat(jvmpath, &s) == 0) {
 791         JLI_TraceLauncher("yes.\n");
 792         return JNI_TRUE;
 793     } else {
 794         JLI_TraceLauncher("no.\n");
 795         return JNI_FALSE;
 796     }
 797 }
 798 
 799 /*
 800  * Find path to JRE based on .exe's location or registry settings.
 801  */
 802 static jboolean
 803 GetJREPath(char *path, jint pathsize, const char * arch, jboolean speculative)
 804 {
 805     char libjava[MAXPATHLEN];
 806 
 807     if (GetApplicationHome(path, pathsize)) {
 808         /* Is JRE co-located with the application? */
 809         JLI_Snprintf(libjava, sizeof(libjava), "%s/lib/%s/" JAVA_DLL, path, arch);
 810         if (access(libjava, F_OK) == 0) {
 811             JLI_TraceLauncher("JRE path is %s\n", path);
 812             return JNI_TRUE;
 813         }
 814 
 815         /* Does the app ship a private JRE in <apphome>/jre directory? */
 816         JLI_Snprintf(libjava, sizeof(libjava), "%s/jre/lib/%s/" JAVA_DLL, path, arch);
 817         if (access(libjava, F_OK) == 0) {
 818             JLI_StrCat(path, "/jre");
 819             JLI_TraceLauncher("JRE path is %s\n", path);
 820             return JNI_TRUE;
 821         }
 822     }
 823 
 824     if (!speculative)
 825       JLI_ReportErrorMessage(JRE_ERROR8 JAVA_DLL);
 826     return JNI_FALSE;
 827 }
 828 
 829 jboolean
 830 LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)
 831 {
 832     void *libjvm;
 833 
 834     JLI_TraceLauncher("JVM path is %s\n", jvmpath);
 835 
 836     libjvm = dlopen(jvmpath, RTLD_NOW + RTLD_GLOBAL);
 837     if (libjvm == NULL) {
 838 #if defined(__solaris__) && defined(__sparc) && !defined(_LP64) /* i.e. 32-bit sparc */
 839       FILE * fp;
 840       Elf32_Ehdr elf_head;
 841       int count;
 842       int location;
 843 
 844       fp = fopen(jvmpath, "r");
 845       if (fp == NULL) {
 846         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
 847         return JNI_FALSE;
 848       }
 849 
 850       /* read in elf header */
 851       count = fread((void*)(&elf_head), sizeof(Elf32_Ehdr), 1, fp);
 852       fclose(fp);
 853       if (count < 1) {
 854         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
 855         return JNI_FALSE;
 856       }
 857 
 858       /*
 859        * Check for running a server vm (compiled with -xarch=v8plus)
 860        * on a stock v8 processor.  In this case, the machine type in
 861        * the elf header would not be included the architecture list
 862        * provided by the isalist command, which is turn is gotten from
 863        * sysinfo.  This case cannot occur on 64-bit hardware and thus
 864        * does not have to be checked for in binaries with an LP64 data
 865        * model.
 866        */
 867       if (elf_head.e_machine == EM_SPARC32PLUS) {
 868         char buf[257];  /* recommended buffer size from sysinfo man
 869                            page */
 870         long length;
 871         char* location;
 872 
 873         length = sysinfo(SI_ISALIST, buf, 257);
 874         if (length > 0) {
 875             location = JLI_StrStr(buf, "sparcv8plus ");
 876           if (location == NULL) {
 877             JLI_ReportErrorMessage(JVM_ERROR3);
 878             return JNI_FALSE;
 879           }
 880         }
 881       }
 882 #endif
 883         JLI_ReportErrorMessage(DLL_ERROR1, __LINE__);
 884         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
 885         return JNI_FALSE;
 886     }
 887 
 888     ifn->CreateJavaVM = (CreateJavaVM_t)
 889         dlsym(libjvm, "JNI_CreateJavaVM");
 890     if (ifn->CreateJavaVM == NULL) {
 891         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
 892         return JNI_FALSE;
 893     }
 894 
 895     ifn->GetDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs_t)
 896         dlsym(libjvm, "JNI_GetDefaultJavaVMInitArgs");
 897     if (ifn->GetDefaultJavaVMInitArgs == NULL) {
 898         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
 899         return JNI_FALSE;
 900     }
 901 
 902     ifn->GetCreatedJavaVMs = (GetCreatedJavaVMs_t)
 903         dlsym(libjvm, "JNI_GetCreatedJavaVMs");
 904     if (ifn->GetCreatedJavaVMs == NULL) {
 905         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
 906         return JNI_FALSE;
 907     }
 908 
 909     return JNI_TRUE;
 910 }
 911 
 912 /*
 913  * Compute the name of the executable
 914  *
 915  * In order to re-exec securely we need the absolute path of the
 916  * executable. On Solaris getexecname(3c) may not return an absolute
 917  * path so we use dladdr to get the filename of the executable and
 918  * then use realpath to derive an absolute path. From Solaris 9
 919  * onwards the filename returned in DL_info structure from dladdr is
 920  * an absolute pathname so technically realpath isn't required.
 921  * On Linux we read the executable name from /proc/self/exe.
 922  * As a fallback, and for platforms other than Solaris and Linux,
 923  * we use FindExecName to compute the executable name.
 924  */
 925 const char*
 926 SetExecname(char **argv)
 927 {
 928     char* exec_path = NULL;
 929 #if defined(__solaris__)
 930     {
 931         Dl_info dlinfo;
 932         int (*fptr)();
 933 
 934         fptr = (int (*)())dlsym(RTLD_DEFAULT, "main");
 935         if (fptr == NULL) {
 936             JLI_ReportErrorMessage(DLL_ERROR3, dlerror());
 937             return JNI_FALSE;
 938         }
 939 
 940         if (dladdr((void*)fptr, &dlinfo)) {
 941             char *resolved = (char*)JLI_MemAlloc(PATH_MAX+1);
 942             if (resolved != NULL) {
 943                 exec_path = realpath(dlinfo.dli_fname, resolved);
 944                 if (exec_path == NULL) {
 945                     JLI_MemFree(resolved);
 946                 }
 947             }
 948         }
 949     }
 950 #elif defined(__linux__)
 951     {
 952         const char* self = "/proc/self/exe";
 953         char buf[PATH_MAX+1];
 954         int len = readlink(self, buf, PATH_MAX);
 955         if (len >= 0) {
 956             buf[len] = '\0';            /* readlink(2) doesn't NUL terminate */
 957             exec_path = JLI_StringDup(buf);
 958         }
 959     }
 960 #else /* !__solaris__ && !__linux__ */
 961     {
 962         /* Not implemented */
 963     }
 964 #endif
 965 
 966     if (exec_path == NULL) {
 967         exec_path = FindExecName(argv[0]);
 968     }
 969     execname = exec_path;
 970     return exec_path;
 971 }
 972 
 973 /* --- Splash Screen shared library support --- */
 974 static const char* SPLASHSCREEN_SO = JNI_LIB_NAME("splashscreen");
 975 static void* hSplashLib = NULL;
 976 
 977 void* SplashProcAddress(const char* name) {
 978     if (!hSplashLib) {
 979         int ret;
 980         char jrePath[MAXPATHLEN];
 981         char splashPath[MAXPATHLEN];
 982 
 983         if (!GetJREPath(jrePath, sizeof(jrePath), GetArch(), JNI_FALSE)) {
 984             JLI_ReportErrorMessage(JRE_ERROR1);
 985             return NULL;
 986         }
 987         ret = JLI_Snprintf(splashPath, sizeof(splashPath), "%s/lib/%s/%s",
 988                      jrePath, GetArch(), SPLASHSCREEN_SO);
 989 
 990         if (ret >= (int) sizeof(splashPath)) {
 991             JLI_ReportErrorMessage(JRE_ERROR11);
 992             return NULL;
 993         }
 994         if (ret < 0) {
 995             JLI_ReportErrorMessage(JRE_ERROR13);
 996             return NULL;
 997         }
 998         hSplashLib = dlopen(splashPath, RTLD_LAZY | RTLD_GLOBAL);
 999         JLI_TraceLauncher("Info: loaded %s\n", splashPath);
1000     }
1001     if (hSplashLib) {
1002         void* sym = dlsym(hSplashLib, name);
1003         return sym;
1004     } else {
1005         return NULL;
1006     }
1007 }
1008 
1009 void SplashFreeLibrary() {
1010     if (hSplashLib) {
1011         dlclose(hSplashLib);
1012         hSplashLib = NULL;
1013     }
1014 }
1015 
1016 /*
1017  * Block current thread and continue execution in a new thread
1018  */
1019 int
1020 ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void * args) {
1021     int rslt;
1022 #ifndef __solaris__
1023     pthread_t tid;
1024     pthread_attr_t attr;
1025     pthread_attr_init(&attr);
1026     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1027 
1028     if (stack_size > 0) {
1029       pthread_attr_setstacksize(&attr, stack_size);
1030     }
1031 
1032     if (pthread_create(&tid, &attr, (void *(*)(void*))continuation, (void*)args) == 0) {
1033       void * tmp;
1034       pthread_join(tid, &tmp);
1035       rslt = (int)tmp;
1036     } else {
1037      /*
1038       * Continue execution in current thread if for some reason (e.g. out of
1039       * memory/LWP)  a new thread can't be created. This will likely fail
1040       * later in continuation as JNI_CreateJavaVM needs to create quite a
1041       * few new threads, anyway, just give it a try..
1042       */
1043       rslt = continuation(args);
1044     }
1045 
1046     pthread_attr_destroy(&attr);
1047 #else /* __solaris__ */
1048     thread_t tid;
1049     long flags = 0;
1050     if (thr_create(NULL, stack_size, (void *(*)(void *))continuation, args, flags, &tid) == 0) {
1051       void * tmp;
1052       thr_join(tid, NULL, &tmp);
1053       rslt = (int)tmp;
1054     } else {
1055       /* See above. Continue in current thread if thr_create() failed */
1056       rslt = continuation(args);
1057     }
1058 #endif /* !__solaris__ */
1059     return rslt;
1060 }
1061 
1062 /* Coarse estimation of number of digits assuming the worst case is a 64-bit pid. */
1063 #define MAX_PID_STR_SZ   20
1064 
1065 void SetJavaLauncherPlatformProps() {
1066    /* Linux only */
1067 #ifdef __linux__
1068     const char *substr = "-Dsun.java.launcher.pid=";
1069     char *pid_prop_str = (char *)JLI_MemAlloc(JLI_StrLen(substr) + MAX_PID_STR_SZ + 1);
1070     sprintf(pid_prop_str, "%s%d", substr, getpid());
1071     AddOption(pid_prop_str, NULL);
1072 #endif /* __linux__ */
1073 }
1074 
1075 int
1076 JVMInit(InvocationFunctions* ifn, jlong threadStackSize,
1077         int argc, char **argv,
1078         int mode, char *what, int ret)
1079 {
1080     ShowSplashScreen();
1081     return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret);
1082 }
1083 
1084 void
1085 PostJVMInit(JNIEnv *env, jstring mainClass, JavaVM *vm)
1086 {
1087     // stubbed out for windows and *nixes.
1088 }
1089 
1090 void
1091 RegisterThread()
1092 {
1093     // stubbed out for windows and *nixes.
1094 }
1095 
1096 /*
1097  * on unix, we return a false to indicate this option is not applicable
1098  */
1099 jboolean
1100 ProcessPlatformOption(const char *arg)
1101 {
1102     return JNI_FALSE;
1103 }