1 /*
   2  * Copyright (c) 1999, 2010, 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 
  26 #include "java.h"
  27 #include <dirent.h>
  28 #include <dlfcn.h>
  29 #include <fcntl.h>
  30 #include <inttypes.h>
  31 #include <stdio.h>
  32 #include <string.h>
  33 #include <stdlib.h>
  34 #include <limits.h>
  35 #include <sys/stat.h>
  36 #include <unistd.h>
  37 #include <sys/types.h>
  38 
  39 #ifndef GAMMA
  40 #include "manifest_info.h"
  41 #include "version_comp.h"
  42 #endif
  43 
  44 #if defined(__linux__) || defined(_ALLBSD_SOURCE)
  45 #include <pthread.h>
  46 #else
  47 #include <thread.h>
  48 #endif
  49 
  50 #ifdef __APPLE__
  51 #define JVM_DLL "libjvm.dylib"
  52 #define JAVA_DLL "libjava.dylib"
  53 #define LD_LIBRARY_PATH "DYLD_LIBRARY_PATH"
  54 #else
  55 #define JVM_DLL "libjvm.so"
  56 #define JAVA_DLL "libjava.so"
  57 #define LD_LIBRARY_PATH "LD_LIBRARY_PATH"
  58 #endif
  59 
  60 #ifndef GAMMA   /* launcher.make defines ARCH */
  61 /*
  62  * If a processor / os combination has the ability to run binaries of
  63  * two data models and cohabitation of jre/jdk bits with both data
  64  * models is supported, then DUAL_MODE is defined.  When DUAL_MODE is
  65  * defined, the architecture names for the narrow and wide version of
  66  * the architecture are defined in LIBARCH64NAME and LIBARCH32NAME.  Currently
  67  * only Solaris on sparc/sparcv9 and i586/amd64 is DUAL_MODE; linux
  68  * i586/amd64 could be defined as DUAL_MODE but that is not the
  69  * current policy.
  70  */
  71 
  72 #ifndef LIBARCHNAME
  73 #  error "The macro LIBARCHNAME was not defined on the compile line"
  74 #endif
  75 
  76 #ifdef __sun
  77 #  define DUAL_MODE
  78 #  ifndef LIBARCH32NAME
  79 #    error "The macro LIBARCH32NAME was not defined on the compile line"
  80 #  endif
  81 #  ifndef LIBARCH64NAME
  82 #    error "The macro LIBARCH64NAME was not defined on the compile line"
  83 #  endif
  84 #  include <sys/systeminfo.h>
  85 #  include <sys/elf.h>
  86 #  include <stdio.h>
  87 #endif
  88 
  89 #endif /* ifndef GAMMA */
  90 
  91 /* pointer to environment */
  92 extern char **environ;
  93 
  94 #ifndef GAMMA
  95 /*
  96  *      A collection of useful strings. One should think of these as #define
  97  *      entries, but actual strings can be more efficient (with many compilers).
  98  */
  99 #ifdef __linux__
 100 static const char *system_dir   = "/usr/java";
 101 static const char *user_dir     = "/java";
 102 #else /* Solaris */
 103 static const char *system_dir   = "/usr/jdk";
 104 static const char *user_dir     = "/jdk";
 105 #endif
 106 
 107 #endif /* ifndef GAMMA */
 108 
 109 /*
 110  * Flowchart of launcher execs and options processing on unix
 111  *
 112  * The selection of the proper vm shared library to open depends on
 113  * several classes of command line options, including vm "flavor"
 114  * options (-client, -server) and the data model options, -d32  and
 115  * -d64, as well as a version specification which may have come from
 116  * the command line or from the manifest of an executable jar file.
 117  * The vm selection options are not passed to the running
 118  * virtual machine; they must be screened out by the launcher.
 119  *
 120  * The version specification (if any) is processed first by the
 121  * platform independent routine SelectVersion.  This may result in
 122  * the exec of the specified launcher version.
 123  *
 124  * Typically, the launcher execs at least once to ensure a suitable
 125  * LD_LIBRARY_PATH is in effect for the process.  The first exec
 126  * screens out all the data model options; leaving the choice of data
 127  * model implicit in the binary selected to run.  However, in case no
 128  * exec is done, the data model options are screened out before the vm
 129  * is invoked.
 130  *
 131  *  incoming argv ------------------------------
 132  *  |                                          |
 133  * \|/                                         |
 134  * CheckJVMType                                |
 135  * (removes -client, -server, etc.)            |
 136  *                                            \|/
 137  *                                            CreateExecutionEnvironment
 138  *                                            (removes -d32 and -d64,
 139  *                                             determines desired data model,
 140  *                                             sets up LD_LIBRARY_PATH,
 141  *                                             and exec's)
 142  *                                             |
 143  *  --------------------------------------------
 144  *  |
 145  * \|/
 146  * exec child 1 incoming argv -----------------
 147  *  |                                          |
 148  * \|/                                         |
 149  * CheckJVMType                                |
 150  * (removes -client, -server, etc.)            |
 151  *  |                                         \|/
 152  *  |                                          CreateExecutionEnvironment
 153  *  |                                          (verifies desired data model
 154  *  |                                           is running and acceptable
 155  *  |                                           LD_LIBRARY_PATH;
 156  *  |                                           no-op in child)
 157  *  |
 158  * \|/
 159  * TranslateDashJArgs...
 160  * (Prepare to pass args to vm)
 161  *  |
 162  *  |
 163  *  |
 164  * \|/
 165  * ParseArguments
 166  * (ignores -d32 and -d64,
 167  *  processes version options,
 168  *  creates argument list for vm,
 169  *  etc.)
 170  *
 171  */
 172 
 173 static char *SetExecname(char **argv);
 174 static char * GetExecname();
 175 static jboolean GetJVMPath(const char *jrepath, const char *jvmtype,
 176                            char *jvmpath, jint jvmpathsize, char * arch);
 177 static jboolean GetJREPath(char *path, jint pathsize, char * arch, jboolean speculative);
 178 
 179 #ifndef GAMMA
 180 const char *
 181 GetArch()
 182 {
 183     return LIBARCHNAME;
 184 }
 185 #endif /* ifndef GAMMA */
 186 
 187 void
 188 CreateExecutionEnvironment(int *_argcp,
 189                            char ***_argvp,
 190                            char jrepath[],
 191                            jint so_jrepath,
 192                            char jvmpath[],
 193                            jint so_jvmpath,
 194                            char **original_argv) {
 195   /*
 196    * First, determine if we are running the desired data model.  If we
 197    * are running the desired data model, all the error messages
 198    * associated with calling GetJREPath, ReadKnownVMs, etc. should be
 199    * output.  However, if we are not running the desired data model,
 200    * some of the errors should be suppressed since it is more
 201    * informative to issue an error message based on whether or not the
 202    * os/processor combination has dual mode capabilities.
 203    */
 204 
 205     char *execname = NULL;
 206     int original_argc = *_argcp;
 207     jboolean jvmpathExists;
 208 
 209     /* Compute the name of the executable */
 210     execname = SetExecname(*_argvp);
 211 
 212 #ifndef GAMMA
 213     /* Set the LD_LIBRARY_PATH environment variable, check data model
 214        flags, and exec process, if needed */
 215     {
 216       char *arch        = (char *)GetArch(); /* like sparc or sparcv9 */
 217       char * jvmtype    = NULL;
 218       int argc          = *_argcp;
 219       char **argv       = original_argv;
 220 
 221       char *runpath     = NULL; /* existing effective LD_LIBRARY_PATH
 222                                    setting */
 223 
 224       int running       =       /* What data model is being ILP32 =>
 225                                    32 bit vm; LP64 => 64 bit vm */
 226 #ifdef _LP64
 227         64;
 228 #else
 229       32;
 230 #endif
 231 
 232       int wanted        = running;      /* What data mode is being
 233                                            asked for? Current model is
 234                                            fine unless another model
 235                                            is asked for */
 236 
 237       char* new_runpath = NULL; /* desired new LD_LIBRARY_PATH string */
 238       char* newpath     = NULL; /* path on new LD_LIBRARY_PATH */
 239       char* lastslash   = NULL;
 240 
 241       char** newenvp    = NULL; /* current environment */
 242 
 243       char** newargv    = NULL;
 244       int    newargc    = 0;
 245 #ifdef __sun
 246       char*  dmpath     = NULL;  /* data model specific LD_LIBRARY_PATH,
 247                                     Solaris only */
 248 #endif
 249 
 250       /*
 251        * Starting in 1.5, all unix platforms accept the -d32 and -d64
 252        * options.  On platforms where only one data-model is supported
 253        * (e.g. ia-64 Linux), using the flag for the other data model is
 254        * an error and will terminate the program.
 255        */
 256 
 257       { /* open new scope to declare local variables */
 258         int i;
 259 
 260         newargv = (char **)JLI_MemAlloc((argc+1) * sizeof(*newargv));
 261         newargv[newargc++] = argv[0];
 262 
 263         /* scan for data model arguments and remove from argument list;
 264            last occurrence determines desired data model */
 265         for (i=1; i < argc; i++) {
 266 
 267           if (strcmp(argv[i], "-J-d64") == 0 || strcmp(argv[i], "-d64") == 0) {
 268             wanted = 64;
 269             continue;
 270           }
 271           if (strcmp(argv[i], "-J-d32") == 0 || strcmp(argv[i], "-d32") == 0) {
 272             wanted = 32;
 273             continue;
 274           }
 275           newargv[newargc++] = argv[i];
 276 
 277 #ifdef JAVA_ARGS
 278           if (argv[i][0] != '-')
 279             continue;
 280 #else
 281           if (strcmp(argv[i], "-classpath") == 0 || strcmp(argv[i], "-cp") == 0) {
 282             i++;
 283             if (i >= argc) break;
 284             newargv[newargc++] = argv[i];
 285             continue;
 286           }
 287           if (argv[i][0] != '-') { i++; break; }
 288 #endif
 289         }
 290 
 291         /* copy rest of args [i .. argc) */
 292         while (i < argc) {
 293           newargv[newargc++] = argv[i++];
 294         }
 295         newargv[newargc] = NULL;
 296 
 297         /*
 298          * newargv has all proper arguments here
 299          */
 300 
 301         argc = newargc;
 302         argv = newargv;
 303       }
 304 
 305       /* If the data model is not changing, it is an error if the
 306          jvmpath does not exist */
 307       if (wanted == running) {
 308         /* Find out where the JRE is that we will be using. */
 309         if (!GetJREPath(jrepath, so_jrepath, arch, JNI_FALSE) ) {
 310           fprintf(stderr, "Error: could not find Java 2 Runtime Environment.\n");
 311           exit(2);
 312         }
 313 
 314         /* Find the specified JVM type */
 315         if (ReadKnownVMs(jrepath, arch, JNI_FALSE) < 1) {
 316           fprintf(stderr, "Error: no known VMs. (check for corrupt jvm.cfg file)\n");
 317           exit(1);
 318         }
 319 
 320         jvmpath[0] = '\0';
 321         jvmtype = CheckJvmType(_argcp, _argvp, JNI_FALSE);
 322 
 323         if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, arch )) {
 324           fprintf(stderr, "Error: no `%s' JVM at `%s'.\n", jvmtype, jvmpath);
 325           exit(4);
 326         }
 327       } else {  /* do the same speculatively or exit */
 328 #ifdef DUAL_MODE
 329         if (running != wanted) {
 330           /* Find out where the JRE is that we will be using. */
 331           if (!GetJREPath(jrepath, so_jrepath, ((wanted==64)?LIBARCH64NAME:LIBARCH32NAME), JNI_TRUE)) {
 332             goto EndDataModelSpeculate;
 333           }
 334 
 335           /*
 336            * Read in jvm.cfg for target data model and process vm
 337            * selection options.
 338            */
 339           if (ReadKnownVMs(jrepath, ((wanted==64)?LIBARCH64NAME:LIBARCH32NAME), JNI_TRUE) < 1) {
 340             goto EndDataModelSpeculate;
 341           }
 342           jvmpath[0] = '\0';
 343           jvmtype = CheckJvmType(_argcp, _argvp, JNI_TRUE);
 344           /* exec child can do error checking on the existence of the path */
 345           jvmpathExists = GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath,
 346                                      ((wanted==64)?LIBARCH64NAME:LIBARCH32NAME));
 347 
 348         }
 349       EndDataModelSpeculate: /* give up and let other code report error message */
 350         ;
 351 #else
 352         fprintf(stderr, "Running a %d-bit JVM is not supported on this platform.\n", wanted);
 353         exit(1);
 354 #endif
 355       }
 356 
 357       /*
 358        * We will set the LD_LIBRARY_PATH as follows:
 359        *
 360        *     o          $JVMPATH (directory portion only)
 361        *     o          $JRE/lib/$LIBARCHNAME
 362        *     o          $JRE/../lib/$LIBARCHNAME
 363        *
 364        * followed by the user's previous effective LD_LIBRARY_PATH, if
 365        * any.
 366        */
 367 
 368 #ifdef __sun
 369       /*
 370        * Starting in Solaris 7, ld.so.1 supports three LD_LIBRARY_PATH
 371        * variables:
 372        *
 373        * 1. LD_LIBRARY_PATH -- used for 32 and 64 bit searches if
 374        * data-model specific variables are not set.
 375        *
 376        * 2. LD_LIBRARY_PATH_64 -- overrides and replaces LD_LIBRARY_PATH
 377        * for 64-bit binaries.
 378        *
 379        * 3. LD_LIBRARY_PATH_32 -- overrides and replaces LD_LIBRARY_PATH
 380        * for 32-bit binaries.
 381        *
 382        * The vm uses LD_LIBRARY_PATH to set the java.library.path system
 383        * property.  To shield the vm from the complication of multiple
 384        * LD_LIBRARY_PATH variables, if the appropriate data model
 385        * specific variable is set, we will act as if LD_LIBRARY_PATH had
 386        * the value of the data model specific variant and the data model
 387        * specific variant will be unset.  Note that the variable for the
 388        * *wanted* data model must be used (if it is set), not simply the
 389        * current running data model.
 390        */
 391 
 392       switch(wanted) {
 393       case 0:
 394         if(running == 32) {
 395           dmpath = getenv("LD_LIBRARY_PATH_32");
 396           wanted = 32;
 397         }
 398         else {
 399           dmpath = getenv("LD_LIBRARY_PATH_64");
 400           wanted = 64;
 401         }
 402         break;
 403 
 404       case 32:
 405         dmpath = getenv("LD_LIBRARY_PATH_32");
 406         break;
 407 
 408       case 64:
 409         dmpath = getenv("LD_LIBRARY_PATH_64");
 410         break;
 411 
 412       default:
 413         fprintf(stderr, "Improper value at line %d.", __LINE__);
 414         exit(1); /* unknown value in wanted */
 415         break;
 416       }
 417 
 418       /*
 419        * If dmpath is NULL, the relevant data model specific variable is
 420        * not set and normal LD_LIBRARY_PATH should be used.
 421        */
 422       if( dmpath == NULL) {
 423         runpath = getenv("LD_LIBRARY_PATH");
 424       }
 425       else {
 426         runpath = dmpath;
 427       }
 428 #else
 429       /*
 430        * If not on Solaris, assume only a single LD_LIBRARY_PATH
 431        * variable.
 432        */
 433       runpath = getenv(LD_LIBRARY_PATH);
 434 #endif /* __sun */
 435 
 436 #if defined(__linux__)
 437       /*
 438        * On linux, if a binary is running as sgid or suid, glibc sets
 439        * LD_LIBRARY_PATH to the empty string for security purposes.  (In
 440        * contrast, on Solaris the LD_LIBRARY_PATH variable for a
 441        * privileged binary does not lose its settings; but the dynamic
 442        * linker does apply more scrutiny to the path.) The launcher uses
 443        * the value of LD_LIBRARY_PATH to prevent an exec loop.
 444        * Therefore, if we are running sgid or suid, this function's
 445        * setting of LD_LIBRARY_PATH will be ineffective and we should
 446        * return from the function now.  Getting the right libraries to
 447        * be found must be handled through other mechanisms.
 448        */
 449       if((getgid() != getegid()) || (getuid() != geteuid()) ) {
 450         return;
 451       }
 452 #elif defined(_ALLBSD_SOURCE)
 453       /*
 454        * On BSD, if a binary is running as sgid or suid, libc sets
 455        * LD_LIBRARY_PATH to the empty string for security purposes.  (In
 456        * contrast, on Solaris the LD_LIBRARY_PATH variable for a
 457        * privileged binary does not lose its settings; but the dynamic
 458        * linker does apply more scrutiny to the path.) The launcher uses
 459        * the value of LD_LIBRARY_PATH to prevent an exec loop.
 460        * Therefore, if we are running sgid or suid, this function's
 461        * setting of LD_LIBRARY_PATH will be ineffective and we should
 462        * return from the function now.  Getting the right libraries to
 463        * be found must be handled through other mechanisms.
 464        */
 465       if(issetugid()) {
 466         return;
 467       }
 468 #endif
 469 
 470       /* runpath contains current effective LD_LIBRARY_PATH setting */
 471 
 472       jvmpath = JLI_StringDup(jvmpath);
 473       new_runpath = JLI_MemAlloc( ((runpath!=NULL)?strlen(runpath):0) +
 474                               2*strlen(jrepath) + 2*strlen(arch) +
 475                               strlen(jvmpath) + 52);
 476       newpath = new_runpath + strlen(LD_LIBRARY_PATH "=");
 477 
 478 
 479       /*
 480        * Create desired LD_LIBRARY_PATH value for target data model.
 481        */
 482       {
 483         /* remove the name of the .so from the JVM path */
 484         lastslash = strrchr(jvmpath, '/');
 485         if (lastslash)
 486           *lastslash = '\0';
 487 
 488 
 489         /* jvmpath, ((running != wanted)?((wanted==64)?"/"LIBARCH64NAME:"/.."):""), */
 490 
 491         sprintf(new_runpath, LD_LIBRARY_PATH "="
 492                 "%s:"
 493                 "%s/lib/%s:"
 494                 "%s/../lib/%s",
 495                 jvmpath,
 496 #ifdef DUAL_MODE
 497                 jrepath, ((wanted==64)?LIBARCH64NAME:LIBARCH32NAME),
 498                 jrepath, ((wanted==64)?LIBARCH64NAME:LIBARCH32NAME)
 499 #else
 500                 jrepath, arch,
 501                 jrepath, arch
 502 #endif
 503                 );
 504 
 505 
 506         /*
 507          * Check to make sure that the prefix of the current path is the
 508          * desired environment variable setting.
 509          */
 510         if (runpath != NULL &&
 511             strncmp(newpath, runpath, strlen(newpath))==0 &&
 512             (runpath[strlen(newpath)] == 0 || runpath[strlen(newpath)] == ':') &&
 513             (running == wanted) /* data model does not have to be changed */
 514 #ifdef __sun
 515             && (dmpath == NULL)    /* data model specific variables not set  */
 516 #endif
 517             ) {
 518 
 519           return;
 520 
 521         }
 522       }
 523 
 524       /*
 525        * Place the desired environment setting onto the prefix of
 526        * LD_LIBRARY_PATH.  Note that this prevents any possible infinite
 527        * loop of execv() because we test for the prefix, above.
 528        */
 529       if (runpath != 0) {
 530         strcat(new_runpath, ":");
 531         strcat(new_runpath, runpath);
 532       }
 533 
 534       if( putenv(new_runpath) != 0) {
 535         exit(1); /* problem allocating memory; LD_LIBRARY_PATH not set
 536                     properly */
 537       }
 538 
 539       /*
 540        * Unix systems document that they look at LD_LIBRARY_PATH only
 541        * once at startup, so we have to re-exec the current executable
 542        * to get the changed environment variable to have an effect.
 543        */
 544 
 545 #ifdef __sun
 546       /*
 547        * If dmpath is not NULL, remove the data model specific string
 548        * in the environment for the exec'ed child.
 549        */
 550 
 551       if( dmpath != NULL)
 552         (void)UnsetEnv((wanted==32)?"LD_LIBRARY_PATH_32":"LD_LIBRARY_PATH_64");
 553 #endif
 554 
 555       newenvp = environ;
 556 
 557       {
 558         char *newexec = execname;
 559 #ifdef DUAL_MODE
 560         /*
 561          * If the data model is being changed, the path to the
 562          * executable must be updated accordingly; the executable name
 563          * and directory the executable resides in are separate.  In the
 564          * case of 32 => 64, the new bits are assumed to reside in, e.g.
 565          * "olddir/LIBARCH64NAME/execname"; in the case of 64 => 32,
 566          * the bits are assumed to be in "olddir/../execname".  For example,
 567          *
 568          * olddir/sparcv9/execname
 569          * olddir/amd64/execname
 570          *
 571          * for Solaris SPARC and Linux amd64, respectively.
 572          */
 573 
 574         if (running != wanted) {
 575           char *oldexec = strcpy(JLI_MemAlloc(strlen(execname) + 1), execname);
 576           char *olddir = oldexec;
 577           char *oldbase = strrchr(oldexec, '/');
 578 
 579 
 580           newexec = JLI_MemAlloc(strlen(execname) + 20);
 581           *oldbase++ = 0;
 582           sprintf(newexec, "%s/%s/%s", olddir,
 583                   ((wanted==64) ? LIBARCH64NAME : ".."), oldbase);
 584           argv[0] = newexec;
 585         }
 586 #endif
 587 
 588         (void)fflush(stdout);
 589         (void)fflush(stderr);
 590         execve(newexec, argv, newenvp);
 591         perror("execve()");
 592 
 593         fprintf(stderr, "Error trying to exec %s.\n", newexec);
 594         fprintf(stderr, "Check if file exists and permissions are set correctly.\n");
 595 
 596 #ifdef DUAL_MODE
 597         if (running != wanted) {
 598           fprintf(stderr, "Failed to start a %d-bit JVM process from a %d-bit JVM.\n",
 599                   wanted, running);
 600 #  ifdef __sun
 601 
 602 #    ifdef __sparc
 603           fprintf(stderr, "Verify all necessary J2SE components have been installed.\n" );
 604           fprintf(stderr,
 605                   "(Solaris SPARC 64-bit components must be installed after 32-bit components.)\n" );
 606 #    else
 607           fprintf(stderr, "Either 64-bit processes are not supported by this platform\n");
 608           fprintf(stderr, "or the 64-bit components have not been installed.\n");
 609 #    endif
 610         }
 611 #  endif
 612 #endif
 613 
 614       }
 615 
 616       exit(1);
 617     }
 618 
 619 #else  /* ifndef GAMMA */
 620 
 621   /*
 622    * gamma launcher is simpler in that it doesn't handle VM flavors, data
 623    * model, LD_LIBRARY_PATH, etc. Assuming everything is set-up correctly
 624    * all we need to do here is to return correct path names. See also
 625    * GetJVMPath() and GetApplicationHome().
 626    */
 627 
 628   { char *arch = (char *) ARCH; /* like sparc or sparcv9 */
 629     char *p;
 630 
 631     if (!GetJREPath(jrepath, so_jrepath, arch, JNI_FALSE) ) {
 632       fprintf(stderr, "Error: could not find Java 2 Runtime Environment.\n");
 633       exit(2);
 634     }
 635 
 636     if (!GetJVMPath(jrepath, NULL, jvmpath, so_jvmpath, arch )) {
 637       fprintf(stderr, "Error: no JVM at `%s'.\n", jvmpath);
 638       exit(4);
 639     }
 640   }
 641 
 642 #endif  /* ifndef GAMMA */
 643 }
 644 
 645 
 646 /*
 647  * On Solaris VM choosing is done by the launcher (java.c).
 648  */
 649 static jboolean
 650 GetJVMPath(const char *jrepath, const char *jvmtype,
 651            char *jvmpath, jint jvmpathsize, char * arch)
 652 {
 653     struct stat s;
 654 
 655 #ifndef GAMMA
 656     if (strchr(jvmtype, '/')) {
 657         sprintf(jvmpath, "%s/" JVM_DLL, jvmtype);
 658     } else {
 659         sprintf(jvmpath, "%s/lib/%s/%s/" JVM_DLL, jrepath, arch, jvmtype);
 660     }
 661 #else
 662     /*
 663      * For gamma launcher, JVM is either built-in or in the same directory.
 664      * Either way we return "<exe_path>/libjvm.so" where <exe_path> is the
 665      * directory where gamma launcher is located.
 666      */
 667 
 668     char *p;
 669 
 670     snprintf(jvmpath, jvmpathsize, "%s", GetExecname());
 671     p = strrchr(jvmpath, '/');
 672     if (p) {
 673        /* replace executable name with libjvm.so */
 674        snprintf(p + 1, jvmpathsize - (p + 1 - jvmpath), "%s", JVM_DLL);
 675     } else {
 676        /* this case shouldn't happen */
 677        snprintf(jvmpath, jvmpathsize, "%s", JVM_DLL);
 678     }
 679 #endif /* ifndef GAMMA */
 680 
 681     if (_launcher_debug)
 682       printf("Does `%s' exist ... ", jvmpath);
 683 
 684     if (stat(jvmpath, &s) == 0) {
 685         if (_launcher_debug)
 686           printf("yes.\n");
 687         return JNI_TRUE;
 688     } else {
 689         if (_launcher_debug)
 690           printf("no.\n");
 691         return JNI_FALSE;
 692     }
 693 }
 694 
 695 /*
 696  * Find path to JRE based on .exe's location or registry settings.
 697  */
 698 static jboolean
 699 GetJREPath(char *path, jint pathsize, char * arch, jboolean speculative)
 700 {
 701     char libjava[MAXPATHLEN];
 702 
 703     if (GetApplicationHome(path, pathsize)) {
 704         /* Is JRE co-located with the application? */
 705         sprintf(libjava, "%s/lib/%s/" JAVA_DLL, path, arch);
 706         if (access(libjava, F_OK) == 0) {
 707             goto found;
 708         }
 709 
 710         /* Does the app ship a private JRE in <apphome>/jre directory? */
 711         sprintf(libjava, "%s/jre/lib/%s/" JAVA_DLL, path, arch);
 712         if (access(libjava, F_OK) == 0) {
 713             strcat(path, "/jre");
 714             goto found;
 715         }
 716     }
 717 
 718     if (!speculative)
 719       fprintf(stderr, "Error: could not find " JAVA_DLL "\n");
 720     return JNI_FALSE;
 721 
 722  found:
 723     if (_launcher_debug)
 724       printf("JRE path is %s\n", path);
 725     return JNI_TRUE;
 726 }
 727 
 728 jboolean
 729 LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)
 730 {
 731 #ifdef GAMMA
 732     /* JVM is directly linked with gamma launcher; no dlopen() */
 733     ifn->CreateJavaVM = JNI_CreateJavaVM;
 734     ifn->GetDefaultJavaVMInitArgs = JNI_GetDefaultJavaVMInitArgs;
 735     return JNI_TRUE;
 736 #else
 737    Dl_info dlinfo;
 738     void *libjvm;
 739 
 740     if (_launcher_debug) {
 741         printf("JVM path is %s\n", jvmpath);
 742     }
 743 
 744     libjvm = dlopen(jvmpath, RTLD_NOW + RTLD_GLOBAL);
 745     if (libjvm == NULL) {
 746 #if defined(__sparc) && !defined(_LP64) /* i.e. 32-bit sparc */
 747       FILE * fp;
 748       Elf32_Ehdr elf_head;
 749       int count;
 750       int location;
 751 
 752       fp = fopen(jvmpath, "r");
 753       if(fp == NULL)
 754         goto error;
 755 
 756       /* read in elf header */
 757       count = fread((void*)(&elf_head), sizeof(Elf32_Ehdr), 1, fp);
 758       fclose(fp);
 759       if(count < 1)
 760         goto error;
 761 
 762       /*
 763        * Check for running a server vm (compiled with -xarch=v8plus)
 764        * on a stock v8 processor.  In this case, the machine type in
 765        * the elf header would not be included the architecture list
 766        * provided by the isalist command, which is turn is gotten from
 767        * sysinfo.  This case cannot occur on 64-bit hardware and thus
 768        * does not have to be checked for in binaries with an LP64 data
 769        * model.
 770        */
 771       if(elf_head.e_machine == EM_SPARC32PLUS) {
 772         char buf[257];  /* recommended buffer size from sysinfo man
 773                            page */
 774         long length;
 775         char* location;
 776 
 777         length = sysinfo(SI_ISALIST, buf, 257);
 778         if(length > 0) {
 779           location = strstr(buf, "sparcv8plus ");
 780           if(location == NULL) {
 781             fprintf(stderr, "SPARC V8 processor detected; Server compiler requires V9 or better.\n");
 782             fprintf(stderr, "Use Client compiler on V8 processors.\n");
 783             fprintf(stderr, "Could not create the Java virtual machine.\n");
 784             return JNI_FALSE;
 785           }
 786         }
 787       }
 788 #endif
 789       fprintf(stderr, "dl failure on line %d", __LINE__);
 790       goto error;
 791     }
 792 
 793     ifn->CreateJavaVM = (CreateJavaVM_t)
 794       dlsym(libjvm, "JNI_CreateJavaVM");
 795     if (ifn->CreateJavaVM == NULL)
 796         goto error;
 797 
 798     ifn->GetDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs_t)
 799         dlsym(libjvm, "JNI_GetDefaultJavaVMInitArgs");
 800     if (ifn->GetDefaultJavaVMInitArgs == NULL)
 801       goto error;
 802 
 803     return JNI_TRUE;
 804 
 805 error:
 806     fprintf(stderr, "Error: failed %s, because %s\n", jvmpath, dlerror());
 807     return JNI_FALSE;
 808 #endif /* ifndef GAMMA */
 809 }
 810 
 811 /*
 812  * If app is "/foo/bin/javac", or "/foo/bin/sparcv9/javac" then put
 813  * "/foo" into buf.
 814  */
 815 jboolean
 816 GetApplicationHome(char *buf, jint bufsize)
 817 {
 818 #if defined(__linux__) || defined(_ALLBSD_SOURCE)
 819     char *execname = GetExecname();
 820     if (execname) {
 821         strncpy(buf, execname, bufsize-1);
 822         buf[bufsize-1] = '\0';
 823     } else {
 824         return JNI_FALSE;
 825     }
 826 #else
 827     Dl_info dlinfo;
 828 
 829     dladdr((void *)GetApplicationHome, &dlinfo);
 830     if (realpath(dlinfo.dli_fname, buf) == NULL) {
 831         fprintf(stderr, "Error: realpath(`%s') failed.\n", dlinfo.dli_fname);
 832         return JNI_FALSE;
 833     }
 834 #endif
 835 
 836 #ifdef GAMMA
 837     {
 838        /* gamma launcher uses JAVA_HOME environment variable to find JDK/JRE */
 839        char* java_home_var = getenv("JAVA_HOME");
 840        if (java_home_var == NULL) {
 841           printf("JAVA_HOME must point to a valid JDK/JRE to run gamma\n");
 842           return JNI_FALSE;
 843        }
 844        snprintf(buf, bufsize, "%s", java_home_var);
 845     }
 846 #else
 847     if (strrchr(buf, '/') == 0) {
 848         buf[0] = '\0';
 849         return JNI_FALSE;
 850     }
 851     *(strrchr(buf, '/')) = '\0';        /* executable file      */
 852     if (strlen(buf) < 4 || strrchr(buf, '/') == 0) {
 853         buf[0] = '\0';
 854         return JNI_FALSE;
 855     }
 856     if (strcmp("/bin", buf + strlen(buf) - 4) != 0)
 857         *(strrchr(buf, '/')) = '\0';    /* sparcv9 or amd64     */
 858     if (strlen(buf) < 4 || strcmp("/bin", buf + strlen(buf) - 4) != 0) {
 859         buf[0] = '\0';
 860         return JNI_FALSE;
 861     }
 862     *(strrchr(buf, '/')) = '\0';        /* bin                  */
 863 #endif /* ifndef GAMMA */
 864 
 865     return JNI_TRUE;
 866 }
 867 
 868 
 869 /*
 870  * Return true if the named program exists
 871  */
 872 static int
 873 ProgramExists(char *name)
 874 {
 875     struct stat sb;
 876     if (stat(name, &sb) != 0) return 0;
 877     if (S_ISDIR(sb.st_mode)) return 0;
 878     return (sb.st_mode & S_IEXEC) != 0;
 879 }
 880 
 881 
 882 /*
 883  * Find a command in a directory, returning the path.
 884  */
 885 static char *
 886 Resolve(char *indir, char *cmd)
 887 {
 888     char name[PATH_MAX + 2], *real;
 889 
 890     if ((strlen(indir) + strlen(cmd) + 1)  > PATH_MAX) return 0;
 891     sprintf(name, "%s%c%s", indir, FILE_SEPARATOR, cmd);
 892     if (!ProgramExists(name)) return 0;
 893     real = JLI_MemAlloc(PATH_MAX + 2);
 894     if (!realpath(name, real))
 895         strcpy(real, name);
 896     return real;
 897 }
 898 
 899 
 900 /*
 901  * Find a path for the executable
 902  */
 903 static char *
 904 FindExecName(char *program)
 905 {
 906     char cwdbuf[PATH_MAX+2];
 907     char *path;
 908     char *tmp_path;
 909     char *f;
 910     char *result = NULL;
 911 
 912     /* absolute path? */
 913     if (*program == FILE_SEPARATOR ||
 914         (FILE_SEPARATOR=='\\' && strrchr(program, ':')))
 915         return Resolve("", program+1);
 916 
 917     /* relative path? */
 918     if (strrchr(program, FILE_SEPARATOR) != 0) {
 919         char buf[PATH_MAX+2];
 920         return Resolve(getcwd(cwdbuf, sizeof(cwdbuf)), program);
 921     }
 922 
 923     /* from search path? */
 924     path = getenv("PATH");
 925     if (!path || !*path) path = ".";
 926     tmp_path = JLI_MemAlloc(strlen(path) + 2);
 927     strcpy(tmp_path, path);
 928 
 929     for (f=tmp_path; *f && result==0; ) {
 930         char *s = f;
 931         while (*f && (*f != PATH_SEPARATOR)) ++f;
 932         if (*f) *f++ = 0;
 933         if (*s == FILE_SEPARATOR)
 934             result = Resolve(s, program);
 935         else {
 936             /* relative path element */
 937             char dir[2*PATH_MAX];
 938             sprintf(dir, "%s%c%s", getcwd(cwdbuf, sizeof(cwdbuf)),
 939                     FILE_SEPARATOR, s);
 940             result = Resolve(dir, program);
 941         }
 942         if (result != 0) break;
 943     }
 944 
 945     JLI_MemFree(tmp_path);
 946     return result;
 947 }
 948 
 949 
 950 /* Store the name of the executable once computed */
 951 static char *execname = NULL;
 952 
 953 /*
 954  * Compute the name of the executable
 955  *
 956  * In order to re-exec securely we need the absolute path of the
 957  * executable. On Solaris getexecname(3c) may not return an absolute
 958  * path so we use dladdr to get the filename of the executable and
 959  * then use realpath to derive an absolute path. From Solaris 9
 960  * onwards the filename returned in DL_info structure from dladdr is
 961  * an absolute pathname so technically realpath isn't required.
 962  * On Linux we read the executable name from /proc/self/exe.
 963  * As a fallback, and for platforms other than Solaris and Linux,
 964  * we use FindExecName to compute the executable name.
 965  */
 966 static char *
 967 SetExecname(char **argv)
 968 {
 969     char* exec_path = NULL;
 970 
 971     if (execname != NULL)       /* Already determined */
 972         return (execname);
 973 
 974 #if defined(__sun)
 975     {
 976         Dl_info dlinfo;
 977         if (dladdr((void*)&SetExecname, &dlinfo)) {
 978             char *resolved = (char*)JLI_MemAlloc(PATH_MAX+1);
 979             if (resolved != NULL) {
 980                 exec_path = realpath(dlinfo.dli_fname, resolved);
 981                 if (exec_path == NULL) {
 982                     JLI_MemFree(resolved);
 983                 }
 984             }
 985         }
 986     }
 987 #elif defined(__linux__)
 988     {
 989         const char* self = "/proc/self/exe";
 990         char buf[PATH_MAX+1];
 991         int len = readlink(self, buf, PATH_MAX);
 992         if (len >= 0) {
 993             buf[len] = '\0';            /* readlink doesn't nul terminate */
 994             exec_path = JLI_StringDup(buf);
 995         }
 996     }
 997 #else /* !__sun && !__linux */
 998     {
 999         /* Not implemented */
1000     }
1001 #endif
1002 
1003     if (exec_path == NULL) {
1004         exec_path = FindExecName(argv[0]);
1005     }
1006     execname = exec_path;
1007     return exec_path;
1008 }
1009 
1010 /*
1011  * Return the name of the executable.  Used in java_md.c to find the JRE area.
1012  */
1013 static char *
1014 GetExecname() {
1015   return execname;
1016 }
1017 
1018 void ReportErrorMessage(char * message, jboolean always) {
1019   if (always) {
1020     fprintf(stderr, "%s\n", message);
1021   }
1022 }
1023 
1024 void ReportErrorMessage2(char * format, char * string, jboolean always) {
1025   if (always) {
1026     fprintf(stderr, format, string);
1027     fprintf(stderr, "\n");
1028   }
1029 }
1030 
1031 void  ReportExceptionDescription(JNIEnv * env) {
1032   (*env)->ExceptionDescribe(env);
1033 }
1034 
1035 /*
1036  * Return JNI_TRUE for an option string that has no effect but should
1037  * _not_ be passed on to the vm; return JNI_FALSE otherwise.  On
1038  * Solaris SPARC, this screening needs to be done if:
1039  * 1) LD_LIBRARY_PATH does _not_ need to be reset and
1040  * 2) -d32 or -d64 is passed to a binary with a matching data model
1041  *    (the exec in SetLibraryPath removes -d<n> options and points the
1042  *    exec to the proper binary).  When this exec is not done, these options
1043  *    would end up getting passed onto the vm.
1044  */
1045 jboolean RemovableMachineDependentOption(char * option) {
1046   /*
1047    * Unconditionally remove both -d32 and -d64 options since only
1048    * the last such options has an effect; e.g.
1049    * java -d32 -d64 -d32 -version
1050    * is equivalent to
1051    * java -d32 -version
1052    */
1053 
1054   if( (strcmp(option, "-d32")  == 0 ) ||
1055       (strcmp(option, "-d64")  == 0 ))
1056     return JNI_TRUE;
1057   else
1058     return JNI_FALSE;
1059 }
1060 
1061 void PrintMachineDependentOptions() {
1062       fprintf(stdout,
1063         "    -d32          use a 32-bit data model if available\n"
1064         "\n"
1065         "    -d64          use a 64-bit data model if available\n");
1066       return;
1067 }
1068 
1069 #ifndef GAMMA
1070 /*
1071  * The following methods (down to ServerClassMachine()) answer
1072  * the question about whether a machine is a "server-class"
1073  * machine.  A server-class machine is loosely defined as one
1074  * with 2 or more processors and 2 gigabytes or more physical
1075  * memory.  The definition of a processor is a physical package,
1076  * not a hyperthreaded chip masquerading as a multi-processor.
1077  * The definition of memory is also somewhat fuzzy, since x86
1078  * machines seem not to report all the memory in their DIMMs, we
1079  * think because of memory mapping of graphics cards, etc.
1080  *
1081  * This code is somewhat more confused with #ifdef's than we'd
1082  * like because this file is used by both Solaris and Linux
1083  * platforms, and so needs to be parameterized for SPARC and
1084  * i586 hardware.  The other Linux platforms (amd64 and ia64)
1085  * don't even ask this question, because they only come with
1086  * server JVMs.  */
1087 
1088 # define KB (1024UL)
1089 # define MB (1024UL * KB)
1090 # define GB (1024UL * MB)
1091 
1092 /* Compute physical memory by asking the OS */
1093 uint64_t
1094 physical_memory(void) {
1095   const uint64_t pages     = (uint64_t) sysconf(_SC_PHYS_PAGES);
1096   const uint64_t page_size = (uint64_t) sysconf(_SC_PAGESIZE);
1097   const uint64_t result    = pages * page_size;
1098 # define UINT64_FORMAT "%" PRIu64
1099 
1100   if (_launcher_debug) {
1101     printf("pages: " UINT64_FORMAT
1102            "  page_size: " UINT64_FORMAT
1103            "  physical memory: " UINT64_FORMAT " (%.3fGB)\n",
1104            pages, page_size, result, result / (double) GB);
1105   }
1106   return result;
1107 }
1108 
1109 #if defined(__sun) && defined(__sparc)
1110 
1111 /* Methods for solaris-sparc: these are easy. */
1112 
1113 /* Ask the OS how many processors there are. */
1114 unsigned long
1115 physical_processors(void) {
1116   const unsigned long sys_processors = sysconf(_SC_NPROCESSORS_CONF);
1117 
1118   if (_launcher_debug) {
1119     printf("sysconf(_SC_NPROCESSORS_CONF): %lu\n", sys_processors);
1120   }
1121   return sys_processors;
1122 }
1123 
1124 /* The solaris-sparc version of the "server-class" predicate. */
1125 jboolean
1126 solaris_sparc_ServerClassMachine(void) {
1127   jboolean            result            = JNI_FALSE;
1128   /* How big is a server class machine? */
1129   const unsigned long server_processors = 2UL;
1130   const uint64_t      server_memory     = 2UL * GB;
1131   const uint64_t      actual_memory     = physical_memory();
1132 
1133   /* Is this a server class machine? */
1134   if (actual_memory >= server_memory) {
1135     const unsigned long actual_processors = physical_processors();
1136     if (actual_processors >= server_processors) {
1137       result = JNI_TRUE;
1138     }
1139   }
1140   if (_launcher_debug) {
1141     printf("solaris_" LIBARCHNAME "_ServerClassMachine: %s\n",
1142            (result == JNI_TRUE ? "JNI_TRUE" : "JNI_FALSE"));
1143   }
1144   return result;
1145 }
1146 
1147 #endif /* __sun && __sparc */
1148 
1149 #if defined(__sun) && defined(i586)
1150 
1151 /*
1152  * A utility method for asking the CPU about itself.
1153  * There's a corresponding version of linux-i586
1154  * because the compilers are different.
1155  */
1156 void
1157 get_cpuid(uint32_t arg,
1158           uint32_t* eaxp,
1159           uint32_t* ebxp,
1160           uint32_t* ecxp,
1161           uint32_t* edxp) {
1162 #ifdef _LP64
1163   asm(
1164   /* rbx is a callee-saved register */
1165       " movq    %rbx, %r11  \n"
1166   /* rdx and rcx are 3rd and 4th argument registers */
1167       " movq    %rdx, %r10  \n"
1168       " movq    %rcx, %r9   \n"
1169       " movl    %edi, %eax  \n"
1170       " cpuid               \n"
1171       " movl    %eax, (%rsi)\n"
1172       " movl    %ebx, (%r10)\n"
1173       " movl    %ecx, (%r9) \n"
1174       " movl    %edx, (%r8) \n"
1175   /* Restore rbx */
1176       " movq    %r11, %rbx");
1177 #else
1178   /* EBX is a callee-saved register */
1179   asm(" pushl   %ebx");
1180   /* Need ESI for storing through arguments */
1181   asm(" pushl   %esi");
1182   asm(" movl    8(%ebp), %eax   \n"
1183       " cpuid                   \n"
1184       " movl    12(%ebp), %esi  \n"
1185       " movl    %eax, (%esi)    \n"
1186       " movl    16(%ebp), %esi  \n"
1187       " movl    %ebx, (%esi)    \n"
1188       " movl    20(%ebp), %esi  \n"
1189       " movl    %ecx, (%esi)    \n"
1190       " movl    24(%ebp), %esi  \n"
1191       " movl    %edx, (%esi)      ");
1192   /* Restore ESI and EBX */
1193   asm(" popl    %esi");
1194   /* Restore EBX */
1195   asm(" popl    %ebx");
1196 #endif
1197 }
1198 
1199 #endif /* __sun && i586 */
1200 
1201 #if (defined(__linux__) || defined(_ALLBSD_SOURCE)) && defined(i586)
1202 
1203 /*
1204  * A utility method for asking the CPU about itself.
1205  * There's a corresponding version of solaris-i586
1206  * because the compilers are different.
1207  */
1208 void
1209 get_cpuid(uint32_t arg,
1210           uint32_t* eaxp,
1211           uint32_t* ebxp,
1212           uint32_t* ecxp,
1213           uint32_t* edxp) {
1214 #ifdef _LP64
1215   __asm__ volatile (/* Instructions */
1216                     "   movl    %4, %%eax  \n"
1217                     "   cpuid              \n"
1218                     "   movl    %%eax, (%0)\n"
1219                     "   movl    %%ebx, (%1)\n"
1220                     "   movl    %%ecx, (%2)\n"
1221                     "   movl    %%edx, (%3)\n"
1222                     : /* Outputs */
1223                     : /* Inputs */
1224                     "r" (eaxp),
1225                     "r" (ebxp),
1226                     "r" (ecxp),
1227                     "r" (edxp),
1228                     "r" (arg)
1229                     : /* Clobbers */
1230                     "%rax", "%rbx", "%rcx", "%rdx", "memory"
1231                     );
1232 #else
1233   uint32_t value_of_eax = 0;
1234   uint32_t value_of_ebx = 0;
1235   uint32_t value_of_ecx = 0;
1236   uint32_t value_of_edx = 0;
1237   __asm__ volatile (/* Instructions */
1238                         /* ebx is callee-save, so push it */
1239                     "   pushl   %%ebx      \n"
1240                     "   movl    %4, %%eax  \n"
1241                     "   cpuid              \n"
1242                     "   movl    %%eax, %0  \n"
1243                     "   movl    %%ebx, %1  \n"
1244                     "   movl    %%ecx, %2  \n"
1245                     "   movl    %%edx, %3  \n"
1246                         /* restore ebx */
1247                     "   popl    %%ebx      \n"
1248 
1249                     : /* Outputs */
1250                     "=m" (value_of_eax),
1251                     "=m" (value_of_ebx),
1252                     "=m" (value_of_ecx),
1253                     "=m" (value_of_edx)
1254                     : /* Inputs */
1255                     "m" (arg)
1256                     : /* Clobbers */
1257                     "%eax", "%ecx", "%edx"
1258                     );
1259   *eaxp = value_of_eax;
1260   *ebxp = value_of_ebx;
1261   *ecxp = value_of_ecx;
1262   *edxp = value_of_edx;
1263 #endif
1264 }
1265 
1266 #endif /* __linux__ && i586 */
1267 
1268 #ifdef i586
1269 /*
1270  * Routines shared by solaris-i586 and linux-i586.
1271  */
1272 
1273 enum HyperThreadingSupport_enum {
1274   hts_supported        =  1,
1275   hts_too_soon_to_tell =  0,
1276   hts_not_supported    = -1,
1277   hts_not_pentium4     = -2,
1278   hts_not_intel        = -3
1279 };
1280 typedef enum HyperThreadingSupport_enum HyperThreadingSupport;
1281 
1282 /* Determine if hyperthreading is supported */
1283 HyperThreadingSupport
1284 hyperthreading_support(void) {
1285   HyperThreadingSupport result = hts_too_soon_to_tell;
1286   /* Bits 11 through 8 is family processor id */
1287 # define FAMILY_ID_SHIFT 8
1288 # define FAMILY_ID_MASK 0xf
1289   /* Bits 23 through 20 is extended family processor id */
1290 # define EXT_FAMILY_ID_SHIFT 20
1291 # define EXT_FAMILY_ID_MASK 0xf
1292   /* Pentium 4 family processor id */
1293 # define PENTIUM4_FAMILY_ID 0xf
1294   /* Bit 28 indicates Hyper-Threading Technology support */
1295 # define HT_BIT_SHIFT 28
1296 # define HT_BIT_MASK 1
1297   uint32_t vendor_id[3] = { 0U, 0U, 0U };
1298   uint32_t value_of_eax = 0U;
1299   uint32_t value_of_edx = 0U;
1300   uint32_t dummy        = 0U;
1301 
1302   /* Yes, this is supposed to be [0], [2], [1] */
1303   get_cpuid(0, &dummy, &vendor_id[0], &vendor_id[2], &vendor_id[1]);
1304   if (_launcher_debug) {
1305     printf("vendor: %c %c %c %c %c %c %c %c %c %c %c %c \n",
1306            ((vendor_id[0] >>  0) & 0xff),
1307            ((vendor_id[0] >>  8) & 0xff),
1308            ((vendor_id[0] >> 16) & 0xff),
1309            ((vendor_id[0] >> 24) & 0xff),
1310            ((vendor_id[1] >>  0) & 0xff),
1311            ((vendor_id[1] >>  8) & 0xff),
1312            ((vendor_id[1] >> 16) & 0xff),
1313            ((vendor_id[1] >> 24) & 0xff),
1314            ((vendor_id[2] >>  0) & 0xff),
1315            ((vendor_id[2] >>  8) & 0xff),
1316            ((vendor_id[2] >> 16) & 0xff),
1317            ((vendor_id[2] >> 24) & 0xff));
1318   }
1319   get_cpuid(1, &value_of_eax, &dummy, &dummy, &value_of_edx);
1320   if (_launcher_debug) {
1321     printf("value_of_eax: 0x%x  value_of_edx: 0x%x\n",
1322            value_of_eax, value_of_edx);
1323   }
1324   if ((((value_of_eax >> FAMILY_ID_SHIFT) & FAMILY_ID_MASK) == PENTIUM4_FAMILY_ID) ||
1325       (((value_of_eax >> EXT_FAMILY_ID_SHIFT) & EXT_FAMILY_ID_MASK) != 0)) {
1326     if ((((vendor_id[0] >>  0) & 0xff) == 'G') &&
1327         (((vendor_id[0] >>  8) & 0xff) == 'e') &&
1328         (((vendor_id[0] >> 16) & 0xff) == 'n') &&
1329         (((vendor_id[0] >> 24) & 0xff) == 'u') &&
1330         (((vendor_id[1] >>  0) & 0xff) == 'i') &&
1331         (((vendor_id[1] >>  8) & 0xff) == 'n') &&
1332         (((vendor_id[1] >> 16) & 0xff) == 'e') &&
1333         (((vendor_id[1] >> 24) & 0xff) == 'I') &&
1334         (((vendor_id[2] >>  0) & 0xff) == 'n') &&
1335         (((vendor_id[2] >>  8) & 0xff) == 't') &&
1336         (((vendor_id[2] >> 16) & 0xff) == 'e') &&
1337         (((vendor_id[2] >> 24) & 0xff) == 'l')) {
1338       if (((value_of_edx >> HT_BIT_SHIFT) & HT_BIT_MASK) == HT_BIT_MASK) {
1339         if (_launcher_debug) {
1340           printf("Hyperthreading supported\n");
1341         }
1342         result = hts_supported;
1343       } else {
1344         if (_launcher_debug) {
1345           printf("Hyperthreading not supported\n");
1346         }
1347         result = hts_not_supported;
1348       }
1349     } else {
1350       if (_launcher_debug) {
1351         printf("Not GenuineIntel\n");
1352       }
1353       result = hts_not_intel;
1354     }
1355   } else {
1356     if (_launcher_debug) {
1357       printf("not Pentium 4 or extended\n");
1358     }
1359     result = hts_not_pentium4;
1360   }
1361   return result;
1362 }
1363 
1364 /* Determine how many logical processors there are per CPU */
1365 unsigned int
1366 logical_processors_per_package(void) {
1367   /*
1368    * After CPUID with EAX==1, register EBX bits 23 through 16
1369    * indicate the number of logical processors per package
1370    */
1371 # define NUM_LOGICAL_SHIFT 16
1372 # define NUM_LOGICAL_MASK 0xff
1373   unsigned int result                        = 1U;
1374   const HyperThreadingSupport hyperthreading = hyperthreading_support();
1375 
1376   if (hyperthreading == hts_supported) {
1377     uint32_t value_of_ebx = 0U;
1378     uint32_t dummy        = 0U;
1379 
1380     get_cpuid(1, &dummy, &value_of_ebx, &dummy, &dummy);
1381     result = (value_of_ebx >> NUM_LOGICAL_SHIFT) & NUM_LOGICAL_MASK;
1382     if (_launcher_debug) {
1383       printf("logical processors per package: %u\n", result);
1384     }
1385   }
1386   return result;
1387 }
1388 
1389 /* Compute the number of physical processors, not logical processors */
1390 unsigned long
1391 physical_processors(void) {
1392   const long sys_processors = sysconf(_SC_NPROCESSORS_CONF);
1393   unsigned long result      = sys_processors;
1394 
1395   if (_launcher_debug) {
1396     printf("sysconf(_SC_NPROCESSORS_CONF): %lu\n", sys_processors);
1397   }
1398   if (sys_processors > 1) {
1399     unsigned int logical_processors = logical_processors_per_package();
1400     if (logical_processors > 1) {
1401       result = (unsigned long) sys_processors / logical_processors;
1402     }
1403   }
1404   if (_launcher_debug) {
1405     printf("physical processors: %lu\n", result);
1406   }
1407   return result;
1408 }
1409 
1410 #endif /* i586 */
1411 
1412 #if defined(__sun) && defined(i586)
1413 
1414 /* The definition of a server-class machine for solaris-i586/amd64 */
1415 jboolean
1416 solaris_i586_ServerClassMachine(void) {
1417   jboolean            result            = JNI_FALSE;
1418   /* How big is a server class machine? */
1419   const unsigned long server_processors = 2UL;
1420   const uint64_t      server_memory     = 2UL * GB;
1421   /*
1422    * We seem not to get our full complement of memory.
1423    *     We allow some part (1/8?) of the memory to be "missing",
1424    *     based on the sizes of DIMMs, and maybe graphics cards.
1425    */
1426   const uint64_t      missing_memory    = 256UL * MB;
1427   const uint64_t      actual_memory     = physical_memory();
1428 
1429   /* Is this a server class machine? */
1430   if (actual_memory >= (server_memory - missing_memory)) {
1431     const unsigned long actual_processors = physical_processors();
1432     if (actual_processors >= server_processors) {
1433       result = JNI_TRUE;
1434     }
1435   }
1436   if (_launcher_debug) {
1437     printf("solaris_" LIBARCHNAME "_ServerClassMachine: %s\n",
1438            (result == JNI_TRUE ? "true" : "false"));
1439   }
1440   return result;
1441 }
1442 
1443 #endif /* __sun && i586 */
1444 
1445 #if defined(__linux__) && defined(i586)
1446 
1447 /* The definition of a server-class machine for linux-i586 */
1448 jboolean
1449 linux_i586_ServerClassMachine(void) {
1450   jboolean            result            = JNI_FALSE;
1451   /* How big is a server class machine? */
1452   const unsigned long server_processors = 2UL;
1453   const uint64_t      server_memory     = 2UL * GB;
1454   /*
1455    * We seem not to get our full complement of memory.
1456    *     We allow some part (1/8?) of the memory to be "missing",
1457    *     based on the sizes of DIMMs, and maybe graphics cards.
1458    */
1459   const uint64_t      missing_memory    = 256UL * MB;
1460   const uint64_t      actual_memory     = physical_memory();
1461 
1462   /* Is this a server class machine? */
1463   if (actual_memory >= (server_memory - missing_memory)) {
1464     const unsigned long actual_processors = physical_processors();
1465     if (actual_processors >= server_processors) {
1466       result = JNI_TRUE;
1467     }
1468   }
1469   if (_launcher_debug) {
1470     printf("linux_" LIBARCHNAME "_ServerClassMachine: %s\n",
1471            (result == JNI_TRUE ? "true" : "false"));
1472   }
1473   return result;
1474 }
1475 
1476 #endif /* __linux__ && i586 */
1477 
1478 #if defined(_ALLBSD_SOURCE) && defined(i586)
1479 
1480 /* The definition of a server-class machine for bsd-i586 */
1481 jboolean
1482 bsd_i586_ServerClassMachine(void) {
1483   jboolean            result            = JNI_FALSE;
1484   /* How big is a server class machine? */
1485   const unsigned long server_processors = 2UL;
1486   const uint64_t      server_memory     = 2UL * GB;
1487   /*
1488    * We seem not to get our full complement of memory.
1489    *     We allow some part (1/8?) of the memory to be "missing",
1490    *     based on the sizes of DIMMs, and maybe graphics cards.
1491    */
1492   const uint64_t      missing_memory    = 256UL * MB;
1493   const uint64_t      actual_memory     = physical_memory();
1494 
1495   /* Is this a server class machine? */
1496   if (actual_memory >= (server_memory - missing_memory)) {
1497     const unsigned long actual_processors = physical_processors();
1498     if (actual_processors >= server_processors) {
1499       result = JNI_TRUE;
1500     }
1501   }
1502   if (_launcher_debug) {
1503     printf("linux_" LIBARCHNAME "_ServerClassMachine: %s\n",
1504            (result == JNI_TRUE ? "true" : "false"));
1505   }
1506   return result;
1507 }
1508 
1509 #endif /* _ALLBSD_SOURCE && i586 */
1510 
1511 /* Dispatch to the platform-specific definition of "server-class" */
1512 jboolean
1513 ServerClassMachine(void) {
1514   jboolean result = JNI_FALSE;
1515 #if   defined(NEVER_ACT_AS_SERVER_CLASS_MACHINE)
1516   result = JNI_FALSE;
1517 #elif defined(ALWAYS_ACT_AS_SERVER_CLASS_MACHINE)
1518   result = JNI_TRUE;
1519 #elif defined(__sun) && defined(__sparc)
1520   result = solaris_sparc_ServerClassMachine();
1521 #elif defined(__sun) && defined(i586)
1522   result = solaris_i586_ServerClassMachine();
1523 #elif defined(__linux__) && defined(i586)
1524   result = linux_i586_ServerClassMachine();
1525 #elif defined(_ALLBSD_SOURCE) && defined(i586)
1526   result = bsd_i586_ServerClassMachine();
1527 #else
1528   if (_launcher_debug) {
1529     printf("ServerClassMachine: returns default value of %s\n",
1530            (result == JNI_TRUE ? "true" : "false"));
1531   }
1532 #endif
1533   return result;
1534 }
1535 
1536 /*
1537  *      Since using the file system as a registry is a bit risky, perform
1538  *      additional sanity checks on the identified directory to validate
1539  *      it as a valid jre/sdk.
1540  *
1541  *      Return 0 if the tests fail; otherwise return non-zero (true).
1542  *
1543  *      Note that checking for anything more than the existence of an
1544  *      executable object at bin/java relative to the path being checked
1545  *      will break the regression tests.
1546  */
1547 static int
1548 CheckSanity(char *path, char *dir)
1549 {
1550     char    buffer[PATH_MAX];
1551 
1552     if (strlen(path) + strlen(dir) + 11 > PATH_MAX)
1553         return (0);     /* Silently reject "impossibly" long paths */
1554 
1555     (void)strcat(strcat(strcat(strcpy(buffer, path), "/"), dir), "/bin/java");
1556     return ((access(buffer, X_OK) == 0) ? 1 : 0);
1557 }
1558 
1559 /*
1560  *      Determine if there is an acceptable JRE in the directory dirname.
1561  *      Upon locating the "best" one, return a fully qualified path to
1562  *      it. "Best" is defined as the most advanced JRE meeting the
1563  *      constraints contained in the manifest_info. If no JRE in this
1564  *      directory meets the constraints, return NULL.
1565  *
1566  *      Note that we don't check for errors in reading the directory
1567  *      (which would be done by checking errno).  This is because it
1568  *      doesn't matter if we get an error reading the directory, or
1569  *      we just don't find anything interesting in the directory.  We
1570  *      just return NULL in either case.
1571  *
1572  *      The historical names of j2sdk and j2re were changed to jdk and
1573  *      jre respecively as part of the 1.5 rebranding effort.  Since the
1574  *      former names are legacy on Linux, they must be recognized for
1575  *      all time.  Fortunately, this is a minor cost.
1576  */
1577 static char
1578 *ProcessDir(manifest_info *info, char *dirname)
1579 {
1580     DIR     *dirp;
1581     struct dirent *dp;
1582     char    *best = NULL;
1583     int     offset;
1584     int     best_offset = 0;
1585     char    *ret_str = NULL;
1586     char    buffer[PATH_MAX];
1587 
1588     if ((dirp = opendir(dirname)) == NULL)
1589         return (NULL);
1590 
1591     do {
1592         if ((dp = readdir(dirp)) != NULL) {
1593             offset = 0;
1594             if ((strncmp(dp->d_name, "jre", 3) == 0) ||
1595                 (strncmp(dp->d_name, "jdk", 3) == 0))
1596                 offset = 3;
1597             else if (strncmp(dp->d_name, "j2re", 4) == 0)
1598                 offset = 4;
1599             else if (strncmp(dp->d_name, "j2sdk", 5) == 0)
1600                 offset = 5;
1601             if (offset > 0) {
1602                 if ((JLI_AcceptableRelease(dp->d_name + offset,
1603                     info->jre_version)) && CheckSanity(dirname, dp->d_name))
1604                     if ((best == NULL) || (JLI_ExactVersionId(
1605                       dp->d_name + offset, best + best_offset) > 0)) {
1606                         if (best != NULL)
1607                             JLI_MemFree(best);
1608                         best = JLI_StringDup(dp->d_name);
1609                         best_offset = offset;
1610                     }
1611             }
1612         }
1613     } while (dp != NULL);
1614     (void) closedir(dirp);
1615     if (best == NULL)
1616         return (NULL);
1617     else {
1618         ret_str = JLI_MemAlloc(strlen(dirname) + strlen(best) + 2);
1619         ret_str = strcat(strcat(strcpy(ret_str, dirname), "/"), best);
1620         JLI_MemFree(best);
1621         return (ret_str);
1622     }
1623 }
1624 
1625 /*
1626  *      This is the global entry point. It examines the host for the optimal
1627  *      JRE to be used by scanning a set of directories.  The set of directories
1628  *      is platform dependent and can be overridden by the environment
1629  *      variable JAVA_VERSION_PATH.
1630  *
1631  *      This routine itself simply determines the set of appropriate
1632  *      directories before passing control onto ProcessDir().
1633  */
1634 char*
1635 LocateJRE(manifest_info* info)
1636 {
1637     char        *path;
1638     char        *home;
1639     char        *target = NULL;
1640     char        *dp;
1641     char        *cp;
1642 
1643     /*
1644      * Start by getting JAVA_VERSION_PATH
1645      */
1646     if (info->jre_restrict_search)
1647         path = JLI_StringDup(system_dir);
1648     else if ((path = getenv("JAVA_VERSION_PATH")) != NULL)
1649         path = JLI_StringDup(path);
1650     else
1651         if ((home = getenv("HOME")) != NULL) {
1652             path = (char *)JLI_MemAlloc(strlen(home) + strlen(system_dir) +
1653                 strlen(user_dir) + 2);
1654             path = strcat(strcat(strcat(strcpy(path, home),
1655                 user_dir), ":"), system_dir);
1656         } else
1657             path = JLI_StringDup(system_dir);
1658 
1659     /*
1660      * Step through each directory on the path. Terminate the scan with
1661      * the first directory with an acceptable JRE.
1662      */
1663     cp = dp = path;
1664     while (dp != NULL) {
1665         cp = strchr(dp, (int)':');
1666         if (cp != NULL)
1667             *cp = (char)NULL;
1668         if ((target = ProcessDir(info, dp)) != NULL)
1669             break;
1670         dp = cp;
1671         if (dp != NULL)
1672             dp++;
1673     }
1674     JLI_MemFree(path);
1675     return (target);
1676 }
1677 
1678 /*
1679  * Given a path to a jre to execute, this routine checks if this process
1680  * is indeed that jre.  If not, it exec's that jre.
1681  *
1682  * We want to actually check the paths rather than just the version string
1683  * built into the executable, so that given version specification (and
1684  * JAVA_VERSION_PATH) will yield the exact same Java environment, regardless
1685  * of the version of the arbitrary launcher we start with.
1686  */
1687 void
1688 ExecJRE(char *jre, char **argv)
1689 {
1690     char    wanted[PATH_MAX];
1691     char    *execname;
1692     char    *progname;
1693 
1694     /*
1695      * Resolve the real path to the directory containing the selected JRE.
1696      */
1697     if (realpath(jre, wanted) == NULL) {
1698         fprintf(stderr, "Unable to resolve %s\n", jre);
1699         exit(1);
1700     }
1701 
1702     /*
1703      * Resolve the real path to the currently running launcher.
1704      */
1705     execname = SetExecname(argv);
1706     if (execname == NULL) {
1707         fprintf(stderr, "Unable to resolve current executable\n");
1708         exit(1);
1709     }
1710 
1711     /*
1712      * If the path to the selected JRE directory is a match to the initial
1713      * portion of the path to the currently executing JRE, we have a winner!
1714      * If so, just return.
1715      */
1716     if (strncmp(wanted, execname, strlen(wanted)) == 0)
1717         return;                 /* I am the droid you were looking for */
1718 
1719     /*
1720      * If this isn't the selected version, exec the selected version.
1721      */
1722 #ifdef JAVA_ARGS  /* javac, jar and friends. */
1723     progname = "java";
1724 #else             /* java, oldjava, javaw and friends */
1725 #ifdef PROGNAME
1726     progname = PROGNAME;
1727 #else
1728     progname = *argv;
1729     if ((s = strrchr(progname, FILE_SEPARATOR)) != 0) {
1730         progname = s + 1;
1731     }
1732 #endif /* PROGNAME */
1733 #endif /* JAVA_ARGS */
1734 
1735     /*
1736      * This should never happen (because of the selection code in SelectJRE),
1737      * but check for "impossibly" long path names just because buffer overruns
1738      * can be so deadly.
1739      */
1740     if (strlen(wanted) + strlen(progname) + 6 > PATH_MAX) {
1741         fprintf(stderr, "Path length exceeds maximum length (PATH_MAX)\n");
1742         exit(1);
1743     }
1744 
1745     /*
1746      * Construct the path and exec it.
1747      */
1748     (void)strcat(strcat(wanted, "/bin/"), progname);
1749     argv[0] = progname;
1750     if (_launcher_debug) {
1751         int i;
1752         printf("ReExec Command: %s (%s)\n", wanted, argv[0]);
1753         printf("ReExec Args:");
1754         for (i = 1; argv[i] != NULL; i++)
1755             printf(" %s", argv[i]);
1756         printf("\n");
1757     }
1758     (void)fflush(stdout);
1759     (void)fflush(stderr);
1760     execv(wanted, argv);
1761     perror("execv()");
1762     fprintf(stderr, "Exec of %s failed\n", wanted);
1763     exit(1);
1764 }
1765 #endif /* ifndef GAMMA */
1766 
1767 /*
1768  * "Borrowed" from Solaris 10 where the unsetenv() function is being added
1769  * to libc thanks to SUSv3 (Standard Unix Specification, version 3). As
1770  * such, in the fullness of time this will appear in libc on all relevant
1771  * Solaris/Linux platforms and maybe even the Windows platform.  At that
1772  * time, this stub can be removed.
1773  *
1774  * This implementation removes the environment locking for multithreaded
1775  * applications.  (We don't have access to these mutexes within libc and
1776  * the launcher isn't multithreaded.)  Note that what remains is platform
1777  * independent, because it only relies on attributes that a POSIX environment
1778  * defines.
1779  *
1780  * Returns 0 on success, -1 on failure.
1781  *
1782  * Also removed was the setting of errno.  The only value of errno set
1783  * was EINVAL ("Invalid Argument").
1784  */
1785 
1786 /*
1787  * s1(environ) is name=value
1788  * s2(name) is name(not the form of name=value).
1789  * if names match, return value of 1, else return 0
1790  */
1791 static int
1792 match_noeq(const char *s1, const char *s2)
1793 {
1794         while (*s1 == *s2++) {
1795                 if (*s1++ == '=')
1796                         return (1);
1797         }
1798         if (*s1 == '=' && s2[-1] == '\0')
1799                 return (1);
1800         return (0);
1801 }
1802 
1803 /*
1804  * added for SUSv3 standard
1805  *
1806  * Delete entry from environ.
1807  * Do not free() memory!  Other threads may be using it.
1808  * Keep it around forever.
1809  */
1810 static int
1811 borrowed_unsetenv(const char *name)
1812 {
1813         long    idx;            /* index into environ */
1814 
1815         if (name == NULL || *name == '\0' ||
1816             strchr(name, '=') != NULL) {
1817                 return (-1);
1818         }
1819 
1820         for (idx = 0; environ[idx] != NULL; idx++) {
1821                 if (match_noeq(environ[idx], name))
1822                         break;
1823         }
1824         if (environ[idx] == NULL) {
1825                 /* name not found but still a success */
1826                 return (0);
1827         }
1828         /* squeeze up one entry */
1829         do {
1830                 environ[idx] = environ[idx+1];
1831         } while (environ[++idx] != NULL);
1832 
1833         return (0);
1834 }
1835 /* --- End of "borrowed" code --- */
1836 
1837 /*
1838  * Wrapper for unsetenv() function.
1839  */
1840 int
1841 UnsetEnv(char *name)
1842 {
1843     return(borrowed_unsetenv(name));
1844 }
1845 
1846 /* --- Splash Screen shared library support --- */
1847 
1848 static const char* SPLASHSCREEN_SO = "libsplashscreen.so";
1849 
1850 static void* hSplashLib = NULL;
1851 
1852 void* SplashProcAddress(const char* name) {
1853     if (!hSplashLib) {
1854         hSplashLib = dlopen(SPLASHSCREEN_SO, RTLD_LAZY | RTLD_GLOBAL);
1855     }
1856     if (hSplashLib) {
1857         void* sym = dlsym(hSplashLib, name);
1858         return sym;
1859     } else {
1860         return NULL;
1861     }
1862 }
1863 
1864 void SplashFreeLibrary() {
1865     if (hSplashLib) {
1866         dlclose(hSplashLib);
1867         hSplashLib = NULL;
1868     }
1869 }
1870 
1871 const char *
1872 jlong_format_specifier() {
1873     return "%lld";
1874 }
1875 
1876 /*
1877  * Block current thread and continue execution in a new thread
1878  */
1879 int
1880 ContinueInNewThread(int (JNICALL *continuation)(void *), jlong stack_size, void * args) {
1881     int rslt;
1882 #if defined(__linux__) || defined(_ALLBSD_SOURCE)
1883     pthread_t tid;
1884     pthread_attr_t attr;
1885     pthread_attr_init(&attr);
1886     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1887 
1888     if (stack_size > 0) {
1889       pthread_attr_setstacksize(&attr, stack_size);
1890     }
1891 
1892     if (pthread_create(&tid, &attr, (void *(*)(void*))continuation, (void*)args) == 0) {
1893       void * tmp;
1894       pthread_join(tid, &tmp);
1895       rslt = (int)(intptr_t)tmp;
1896     } else {
1897      /*
1898       * Continue execution in current thread if for some reason (e.g. out of
1899       * memory/LWP)  a new thread can't be created. This will likely fail
1900       * later in continuation as JNI_CreateJavaVM needs to create quite a
1901       * few new threads, anyway, just give it a try..
1902       */
1903       rslt = continuation(args);
1904     }
1905 
1906     pthread_attr_destroy(&attr);
1907 #else
1908     thread_t tid;
1909     long flags = 0;
1910     if (thr_create(NULL, stack_size, (void *(*)(void *))continuation, args, flags, &tid) == 0) {
1911       void * tmp;
1912       thr_join(tid, NULL, &tmp);
1913       rslt = (int)(intptr_t)tmp;
1914     } else {
1915       /* See above. Continue in current thread if thr_create() failed */
1916       rslt = continuation(args);
1917     }
1918 #endif
1919     return rslt;
1920 }
1921 
1922 /* Coarse estimation of number of digits assuming the worst case is a 64-bit pid. */
1923 #define MAX_PID_STR_SZ   20
1924 
1925 void SetJavaLauncherPlatformProps() {
1926    /* Linux only */
1927 #ifdef __linux__
1928     const char *substr = "-Dsun.java.launcher.pid=";
1929     char *pid_prop_str = (char *)JLI_MemAlloc(strlen(substr) + MAX_PID_STR_SZ + 1);
1930     sprintf(pid_prop_str, "%s%d", substr, getpid());
1931     AddOption(pid_prop_str, NULL);
1932 #endif
1933 }