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