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