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