blob: 5d96c2780f009aa702428faca964fd4a0068a5d6 [file] [log] [blame]
J. Duke319a3b92007-12-01 00:00:00 +00001/*
2 * Copyright 1998-2007 Sun Microsystems, Inc. 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. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
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 <sys/stat.h>
35#include <unistd.h>
36#include <sys/types.h>
37#include "manifest_info.h"
38#include "version_comp.h"
39
40#ifdef __linux__
41#include <pthread.h>
42#else
43#include <thread.h>
44#endif
45
46#define JVM_DLL "libjvm.so"
47#define JAVA_DLL "libjava.so"
48
49/*
50 * If a processor / os combination has the ability to run binaries of
51 * two data models and cohabitation of jre/jdk bits with both data
52 * models is supported, then DUAL_MODE is defined. When DUAL_MODE is
53 * defined, the architecture names for the narrow and wide version of
54 * the architecture are defined in LIBARCH64NAME and LIBARCH32NAME. Currently
55 * only Solaris on sparc/sparcv9 and i586/amd64 is DUAL_MODE; linux
56 * i586/amd64 could be defined as DUAL_MODE but that is not the
57 * current policy.
58 */
59
60#ifdef __solaris__
61# define DUAL_MODE
62# ifndef LIBARCH32NAME
63# error "The macro LIBARCH32NAME was not defined on the compile line"
64# endif
65# ifndef LIBARCH64NAME
66# error "The macro LIBARCH64NAME was not defined on the compile line"
67# endif
68# include <sys/systeminfo.h>
69# include <sys/elf.h>
70# include <stdio.h>
71#endif
72
73/* pointer to environment */
74extern char **environ;
75
76/*
77 * A collection of useful strings. One should think of these as #define
78 * entries, but actual strings can be more efficient (with many compilers).
79 */
80#ifdef __linux__
81static const char *system_dir = "/usr/java";
82static const char *user_dir = "/java";
83#else /* Solaris */
84static const char *system_dir = "/usr/jdk";
85static const char *user_dir = "/jdk";
86#endif
87
88/* Store the name of the executable once computed */
89static char *execname = NULL;
90
91/*
92 * Flowchart of launcher execs and options processing on unix
93 *
94 * The selection of the proper vm shared library to open depends on
95 * several classes of command line options, including vm "flavor"
96 * options (-client, -server) and the data model options, -d32 and
97 * -d64, as well as a version specification which may have come from
98 * the command line or from the manifest of an executable jar file.
99 * The vm selection options are not passed to the running
100 * virtual machine; they must be screened out by the launcher.
101 *
102 * The version specification (if any) is processed first by the
103 * platform independent routine SelectVersion. This may result in
104 * the exec of the specified launcher version.
105 *
106 * Typically, the launcher execs at least once to ensure a suitable
107 * LD_LIBRARY_PATH is in effect for the process. The first exec
108 * screens out all the data model options; leaving the choice of data
109 * model implicit in the binary selected to run. However, in case no
110 * exec is done, the data model options are screened out before the vm
111 * is invoked.
112 *
113 * incoming argv ------------------------------
114 * | |
115 * \|/ |
116 * CheckJVMType |
117 * (removes -client, -server, etc.) |
118 * \|/
119 * CreateExecutionEnvironment
120 * (removes -d32 and -d64,
121 * determines desired data model,
122 * sets up LD_LIBRARY_PATH,
123 * and exec's)
124 * |
125 * --------------------------------------------
126 * |
127 * \|/
128 * exec child 1 incoming argv -----------------
129 * | |
130 * \|/ |
131 * CheckJVMType |
132 * (removes -client, -server, etc.) |
133 * | \|/
134 * | CreateExecutionEnvironment
135 * | (verifies desired data model
136 * | is running and acceptable
137 * | LD_LIBRARY_PATH;
138 * | no-op in child)
139 * |
140 * \|/
141 * TranslateDashJArgs...
142 * (Prepare to pass args to vm)
143 * |
144 * |
145 * |
146 * \|/
147 * ParseArguments
148 * (ignores -d32 and -d64,
149 * processes version options,
150 * creates argument list for vm,
151 * etc.)
152 *
153 */
154
155static const char * SetExecname(char **argv);
156static jboolean GetJVMPath(const char *jrepath, const char *jvmtype,
157 char *jvmpath, jint jvmpathsize, const char * arch);
158static jboolean GetJREPath(char *path, jint pathsize, const char * arch, jboolean speculative);
159
160
161#define GetArch() GetArchPath(CURRENT_DATA_MODEL)
162
163const char *
164GetArchPath(int nbits)
165{
166 switch(nbits) {
167#ifdef DUAL_MODE
168 case 32:
169 return LIBARCH32NAME;
170 case 64:
171 return LIBARCH64NAME;
172#endif /* DUAL_MODE */
173 default:
174 return LIBARCHNAME;
175 }
176}
177
178void
179CreateExecutionEnvironment(int *_argcp,
180 char ***_argvp,
181 char jrepath[],
182 jint so_jrepath,
183 char jvmpath[],
184 jint so_jvmpath,
185 char **original_argv) {
186 /*
187 * First, determine if we are running the desired data model. If we
188 * are running the desired data model, all the error messages
189 * associated with calling GetJREPath, ReadKnownVMs, etc. should be
190 * output. However, if we are not running the desired data model,
191 * some of the errors should be suppressed since it is more
192 * informative to issue an error message based on whether or not the
193 * os/processor combination has dual mode capabilities.
194 */
195
196 int original_argc = *_argcp;
197 jboolean jvmpathExists;
198
199 /* Compute/set the name of the executable */
200 SetExecname(*_argvp);
201
202 /* Set the LD_LIBRARY_PATH environment variable, check data model
203 flags, and exec process, if needed */
204 {
205 char *arch = (char *)GetArch(); /* like sparc or sparcv9 */
206 char * jvmtype = NULL;
207 int argc = *_argcp;
208 char **argv = original_argv;
209
210 char *runpath = NULL; /* existing effective LD_LIBRARY_PATH
211 setting */
212
213 int running = CURRENT_DATA_MODEL;
214
215 int wanted = running; /* What data mode is being
216 asked for? Current model is
217 fine unless another model
218 is asked for */
219
220 char* new_runpath = NULL; /* desired new LD_LIBRARY_PATH string */
221 char* newpath = NULL; /* path on new LD_LIBRARY_PATH */
222 char* lastslash = NULL;
223
224 char** newenvp = NULL; /* current environment */
225
226 char** newargv = NULL;
227 int newargc = 0;
228#ifdef __solaris__
229 char* dmpath = NULL; /* data model specific LD_LIBRARY_PATH,
230 Solaris only */
231#endif
232
233 /*
234 * Starting in 1.5, all unix platforms accept the -d32 and -d64
235 * options. On platforms where only one data-model is supported
236 * (e.g. ia-64 Linux), using the flag for the other data model is
237 * an error and will terminate the program.
238 */
239
240 { /* open new scope to declare local variables */
241 int i;
242
243 newargv = (char **)JLI_MemAlloc((argc+1) * sizeof(*newargv));
244 newargv[newargc++] = argv[0];
245
246 /* scan for data model arguments and remove from argument list;
247 last occurrence determines desired data model */
248 for (i=1; i < argc; i++) {
249
250 if (JLI_StrCmp(argv[i], "-J-d64") == 0 || JLI_StrCmp(argv[i], "-d64") == 0) {
251 wanted = 64;
252 continue;
253 }
254 if (JLI_StrCmp(argv[i], "-J-d32") == 0 || JLI_StrCmp(argv[i], "-d32") == 0) {
255 wanted = 32;
256 continue;
257 }
258 newargv[newargc++] = argv[i];
259
260 if (IsJavaArgs()) {
261 if (argv[i][0] != '-') continue;
262 } else {
263 if (JLI_StrCmp(argv[i], "-classpath") == 0 || JLI_StrCmp(argv[i], "-cp") == 0) {
264 i++;
265 if (i >= argc) break;
266 newargv[newargc++] = argv[i];
267 continue;
268 }
269 if (argv[i][0] != '-') { i++; break; }
270 }
271 }
272
273 /* copy rest of args [i .. argc) */
274 while (i < argc) {
275 newargv[newargc++] = argv[i++];
276 }
277 newargv[newargc] = NULL;
278
279 /*
280 * newargv has all proper arguments here
281 */
282
283 argc = newargc;
284 argv = newargv;
285 }
286
287 /* If the data model is not changing, it is an error if the
288 jvmpath does not exist */
289 if (wanted == running) {
290 /* Find out where the JRE is that we will be using. */
291 if (!GetJREPath(jrepath, so_jrepath, arch, JNI_FALSE) ) {
292 ReportErrorMessage(JRE_ERROR1);
293 exit(2);
294 }
295
296 /* Find the specified JVM type */
297 if (ReadKnownVMs(jrepath, arch, JNI_FALSE) < 1) {
298 ReportErrorMessage(CFG_ERROR7);
299 exit(1);
300 }
301
302 jvmpath[0] = '\0';
303 jvmtype = CheckJvmType(_argcp, _argvp, JNI_FALSE);
304
305 if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, arch )) {
306 ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath);
307 exit(4);
308 }
309 } else { /* do the same speculatively or exit */
310#ifdef DUAL_MODE
311 if (running != wanted) {
312 /* Find out where the JRE is that we will be using. */
313 if (!GetJREPath(jrepath, so_jrepath, GetArchPath(wanted), JNI_TRUE)) {
314 goto EndDataModelSpeculate;
315 }
316
317 /*
318 * Read in jvm.cfg for target data model and process vm
319 * selection options.
320 */
321 if (ReadKnownVMs(jrepath, GetArchPath(wanted), JNI_TRUE) < 1) {
322 goto EndDataModelSpeculate;
323 }
324 jvmpath[0] = '\0';
325 jvmtype = CheckJvmType(_argcp, _argvp, JNI_TRUE);
326 /* exec child can do error checking on the existence of the path */
327 jvmpathExists = GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath, GetArchPath(wanted));
328
329 }
330 EndDataModelSpeculate: /* give up and let other code report error message */
331 ;
332#else
333 ReportErrorMessage(JRE_ERROR2, wanted);
334 exit(1);
335#endif
336 }
337
338 /*
339 * We will set the LD_LIBRARY_PATH as follows:
340 *
341 * o $JVMPATH (directory portion only)
342 * o $JRE/lib/$LIBARCHNAME
343 * o $JRE/../lib/$LIBARCHNAME
344 *
345 * followed by the user's previous effective LD_LIBRARY_PATH, if
346 * any.
347 */
348
349#ifdef __solaris__
350 /*
351 * Starting in Solaris 7, ld.so.1 supports three LD_LIBRARY_PATH
352 * variables:
353 *
354 * 1. LD_LIBRARY_PATH -- used for 32 and 64 bit searches if
355 * data-model specific variables are not set.
356 *
357 * 2. LD_LIBRARY_PATH_64 -- overrides and replaces LD_LIBRARY_PATH
358 * for 64-bit binaries.
359 *
360 * 3. LD_LIBRARY_PATH_32 -- overrides and replaces LD_LIBRARY_PATH
361 * for 32-bit binaries.
362 *
363 * The vm uses LD_LIBRARY_PATH to set the java.library.path system
364 * property. To shield the vm from the complication of multiple
365 * LD_LIBRARY_PATH variables, if the appropriate data model
366 * specific variable is set, we will act as if LD_LIBRARY_PATH had
367 * the value of the data model specific variant and the data model
368 * specific variant will be unset. Note that the variable for the
369 * *wanted* data model must be used (if it is set), not simply the
370 * current running data model.
371 */
372
373 switch(wanted) {
374 case 0:
375 if(running == 32) {
376 dmpath = getenv("LD_LIBRARY_PATH_32");
377 wanted = 32;
378 }
379 else {
380 dmpath = getenv("LD_LIBRARY_PATH_64");
381 wanted = 64;
382 }
383 break;
384
385 case 32:
386 dmpath = getenv("LD_LIBRARY_PATH_32");
387 break;
388
389 case 64:
390 dmpath = getenv("LD_LIBRARY_PATH_64");
391 break;
392
393 default:
394 ReportErrorMessage(JRE_ERROR3, __LINE__);
395 exit(1); /* unknown value in wanted */
396 break;
397 }
398
399 /*
400 * If dmpath is NULL, the relevant data model specific variable is
401 * not set and normal LD_LIBRARY_PATH should be used.
402 */
403 if( dmpath == NULL) {
404 runpath = getenv("LD_LIBRARY_PATH");
405 }
406 else {
407 runpath = dmpath;
408 }
409#else
410 /*
411 * If not on Solaris, assume only a single LD_LIBRARY_PATH
412 * variable.
413 */
414 runpath = getenv("LD_LIBRARY_PATH");
415#endif /* __solaris__ */
416
417#ifdef __linux
418 /*
419 * On linux, if a binary is running as sgid or suid, glibc sets
420 * LD_LIBRARY_PATH to the empty string for security purposes. (In
421 * contrast, on Solaris the LD_LIBRARY_PATH variable for a
422 * privileged binary does not lose its settings; but the dynamic
423 * linker does apply more scrutiny to the path.) The launcher uses
424 * the value of LD_LIBRARY_PATH to prevent an exec loop.
425 * Therefore, if we are running sgid or suid, this function's
426 * setting of LD_LIBRARY_PATH will be ineffective and we should
427 * return from the function now. Getting the right libraries to
428 * be found must be handled through other mechanisms.
429 */
430 if((getgid() != getegid()) || (getuid() != geteuid()) ) {
431 return;
432 }
433#endif
434
435 /* runpath contains current effective LD_LIBRARY_PATH setting */
436
437 jvmpath = JLI_StringDup(jvmpath);
438 new_runpath = JLI_MemAlloc( ((runpath!=NULL)?JLI_StrLen(runpath):0) +
439 2*JLI_StrLen(jrepath) + 2*JLI_StrLen(arch) +
440 JLI_StrLen(jvmpath) + 52);
441 newpath = new_runpath + JLI_StrLen("LD_LIBRARY_PATH=");
442
443
444 /*
445 * Create desired LD_LIBRARY_PATH value for target data model.
446 */
447 {
448 /* remove the name of the .so from the JVM path */
449 lastslash = JLI_StrRChr(jvmpath, '/');
450 if (lastslash)
451 *lastslash = '\0';
452
453
454 /* jvmpath, ((running != wanted)?((wanted==64)?"/"LIBARCH64NAME:"/.."):""), */
455
456 sprintf(new_runpath, "LD_LIBRARY_PATH="
457 "%s:"
458 "%s/lib/%s:"
459 "%s/../lib/%s",
460 jvmpath,
461#ifdef DUAL_MODE
462 jrepath, GetArchPath(wanted),
463 jrepath, GetArchPath(wanted)
464#else
465 jrepath, arch,
466 jrepath, arch
467#endif
468 );
469
470
471 /*
472 * Check to make sure that the prefix of the current path is the
473 * desired environment variable setting.
474 */
475 if (runpath != NULL &&
476 JLI_StrNCmp(newpath, runpath, JLI_StrLen(newpath))==0 &&
477 (runpath[JLI_StrLen(newpath)] == 0 || runpath[JLI_StrLen(newpath)] == ':') &&
478 (running == wanted) /* data model does not have to be changed */
479#ifdef __solaris__
480 && (dmpath == NULL) /* data model specific variables not set */
481#endif
482 ) {
483
484 return;
485
486 }
487 }
488
489 /*
490 * Place the desired environment setting onto the prefix of
491 * LD_LIBRARY_PATH. Note that this prevents any possible infinite
492 * loop of execv() because we test for the prefix, above.
493 */
494 if (runpath != 0) {
495 JLI_StrCat(new_runpath, ":");
496 JLI_StrCat(new_runpath, runpath);
497 }
498
499 if( putenv(new_runpath) != 0) {
500 exit(1); /* problem allocating memory; LD_LIBRARY_PATH not set
501 properly */
502 }
503
504 /*
505 * Unix systems document that they look at LD_LIBRARY_PATH only
506 * once at startup, so we have to re-exec the current executable
507 * to get the changed environment variable to have an effect.
508 */
509
510#ifdef __solaris__
511 /*
512 * If dmpath is not NULL, remove the data model specific string
513 * in the environment for the exec'ed child.
514 */
515
516 if( dmpath != NULL)
517 (void)UnsetEnv((wanted==32)?"LD_LIBRARY_PATH_32":"LD_LIBRARY_PATH_64");
518#endif
519
520 newenvp = environ;
521
522 {
523 char *newexec = execname;
524#ifdef DUAL_MODE
525 /*
526 * If the data model is being changed, the path to the
527 * executable must be updated accordingly; the executable name
528 * and directory the executable resides in are separate. In the
529 * case of 32 => 64, the new bits are assumed to reside in, e.g.
530 * "olddir/LIBARCH64NAME/execname"; in the case of 64 => 32,
531 * the bits are assumed to be in "olddir/../execname". For example,
532 *
533 * olddir/sparcv9/execname
534 * olddir/amd64/execname
535 *
536 * for Solaris SPARC and Linux amd64, respectively.
537 */
538
539 if (running != wanted) {
540 char *oldexec = JLI_StrCpy(JLI_MemAlloc(JLI_StrLen(execname) + 1), execname);
541 char *olddir = oldexec;
542 char *oldbase = JLI_StrRChr(oldexec, '/');
543
544
545 newexec = JLI_MemAlloc(JLI_StrLen(execname) + 20);
546 *oldbase++ = 0;
547 sprintf(newexec, "%s/%s/%s", olddir,
548 ((wanted==64) ? LIBARCH64NAME : ".."), oldbase);
549 argv[0] = newexec;
550 }
551#endif
552
553 (void)fflush(stdout);
554 (void)fflush(stderr);
555 execve(newexec, argv, newenvp);
556 ReportErrorMessageSys(JRE_ERROR4, newexec);
557
558#ifdef DUAL_MODE
559 if (running != wanted) {
560 ReportErrorMessage(JRE_ERROR5, wanted, running);
561# ifdef __solaris__
562
563# ifdef __sparc
564 ReportErrorMessage(JRE_ERROR6);
565# else
566 ReportErrorMessage(JRE_ERROR7);
567# endif
568 }
569# endif
570#endif
571
572 }
573
574 exit(1);
575 }
576
577}
578
579
580/*
581 * On Solaris VM choosing is done by the launcher (java.c).
582 */
583static jboolean
584GetJVMPath(const char *jrepath, const char *jvmtype,
585 char *jvmpath, jint jvmpathsize, const char * arch)
586{
587 struct stat s;
588
589 if (JLI_StrChr(jvmtype, '/')) {
590 sprintf(jvmpath, "%s/" JVM_DLL, jvmtype);
591 } else {
592 sprintf(jvmpath, "%s/lib/%s/%s/" JVM_DLL, jrepath, arch, jvmtype);
593 }
594
595 JLI_TraceLauncher("Does `%s' exist ... ", jvmpath);
596
597 if (stat(jvmpath, &s) == 0) {
598 JLI_TraceLauncher("yes.\n");
599 return JNI_TRUE;
600 } else {
601 JLI_TraceLauncher("no.\n");
602 return JNI_FALSE;
603 }
604}
605
606/*
607 * Find path to JRE based on .exe's location or registry settings.
608 */
609static jboolean
610GetJREPath(char *path, jint pathsize, const char * arch, jboolean speculative)
611{
612 char libjava[MAXPATHLEN];
613
614 if (GetApplicationHome(path, pathsize)) {
615 /* Is JRE co-located with the application? */
616 sprintf(libjava, "%s/lib/%s/" JAVA_DLL, path, arch);
617 if (access(libjava, F_OK) == 0) {
618 goto found;
619 }
620
621 /* Does the app ship a private JRE in <apphome>/jre directory? */
622 sprintf(libjava, "%s/jre/lib/%s/" JAVA_DLL, path, arch);
623 if (access(libjava, F_OK) == 0) {
624 JLI_StrCat(path, "/jre");
625 goto found;
626 }
627 }
628
629 if (!speculative)
630 ReportErrorMessage(JRE_ERROR8 JAVA_DLL);
631 return JNI_FALSE;
632
633 found:
634 JLI_TraceLauncher("JRE path is %s\n", path);
635 return JNI_TRUE;
636}
637
638jboolean
639LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)
640{
641 Dl_info dlinfo;
642 void *libjvm;
643
644 JLI_TraceLauncher("JVM path is %s\n", jvmpath);
645
646 libjvm = dlopen(jvmpath, RTLD_NOW + RTLD_GLOBAL);
647 if (libjvm == NULL) {
648#if defined(__solaris__) && defined(__sparc) && !defined(_LP64) /* i.e. 32-bit sparc */
649 FILE * fp;
650 Elf32_Ehdr elf_head;
651 int count;
652 int location;
653
654 fp = fopen(jvmpath, "r");
655 if(fp == NULL)
656 goto error;
657
658 /* read in elf header */
659 count = fread((void*)(&elf_head), sizeof(Elf32_Ehdr), 1, fp);
660 fclose(fp);
661 if(count < 1)
662 goto error;
663
664 /*
665 * Check for running a server vm (compiled with -xarch=v8plus)
666 * on a stock v8 processor. In this case, the machine type in
667 * the elf header would not be included the architecture list
668 * provided by the isalist command, which is turn is gotten from
669 * sysinfo. This case cannot occur on 64-bit hardware and thus
670 * does not have to be checked for in binaries with an LP64 data
671 * model.
672 */
673 if(elf_head.e_machine == EM_SPARC32PLUS) {
674 char buf[257]; /* recommended buffer size from sysinfo man
675 page */
676 long length;
677 char* location;
678
679 length = sysinfo(SI_ISALIST, buf, 257);
680 if(length > 0) {
681 location = JLI_StrStr(buf, "sparcv8plus ");
682 if(location == NULL) {
683 ReportErrorMessage(JVM_ERROR3);
684 return JNI_FALSE;
685 }
686 }
687 }
688#endif
689 ReportErrorMessage(DLL_ERROR1, __LINE__);
690 goto error;
691 }
692
693 ifn->CreateJavaVM = (CreateJavaVM_t)
694 dlsym(libjvm, "JNI_CreateJavaVM");
695 if (ifn->CreateJavaVM == NULL)
696 goto error;
697
698 ifn->GetDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs_t)
699 dlsym(libjvm, "JNI_GetDefaultJavaVMInitArgs");
700 if (ifn->GetDefaultJavaVMInitArgs == NULL)
701 goto error;
702
703 return JNI_TRUE;
704
705error:
706 ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
707 return JNI_FALSE;
708}
709
710/*
711 * If app is "/foo/bin/javac", or "/foo/bin/sparcv9/javac" then put
712 * "/foo" into buf.
713 */
714jboolean
715GetApplicationHome(char *buf, jint bufsize)
716{
717 if (execname != NULL) {
718 JLI_StrNCpy(buf, execname, bufsize-1);
719 buf[bufsize-1] = '\0';
720 } else {
721 return JNI_FALSE;
722 }
723
724 if (JLI_StrRChr(buf, '/') == 0) {
725 buf[0] = '\0';
726 return JNI_FALSE;
727 }
728 *(JLI_StrRChr(buf, '/')) = '\0'; /* executable file */
729 if (JLI_StrLen(buf) < 4 || JLI_StrRChr(buf, '/') == 0) {
730 buf[0] = '\0';
731 return JNI_FALSE;
732 }
733 if (JLI_StrCmp("/bin", buf + JLI_StrLen(buf) - 4) != 0)
734 *(JLI_StrRChr(buf, '/')) = '\0'; /* sparcv9 or amd64 */
735 if (JLI_StrLen(buf) < 4 || JLI_StrCmp("/bin", buf + JLI_StrLen(buf) - 4) != 0) {
736 buf[0] = '\0';
737 return JNI_FALSE;
738 }
739 *(JLI_StrRChr(buf, '/')) = '\0'; /* bin */
740
741 return JNI_TRUE;
742}
743
744
745/*
746 * Return true if the named program exists
747 */
748static int
749ProgramExists(char *name)
750{
751 struct stat sb;
752 if (stat(name, &sb) != 0) return 0;
753 if (S_ISDIR(sb.st_mode)) return 0;
754 return (sb.st_mode & S_IEXEC) != 0;
755}
756
757
758/*
759 * Find a command in a directory, returning the path.
760 */
761static char *
762Resolve(char *indir, char *cmd)
763{
764 char name[PATH_MAX + 2], *real;
765
766 if ((JLI_StrLen(indir) + JLI_StrLen(cmd) + 1) > PATH_MAX) return 0;
767 sprintf(name, "%s%c%s", indir, FILE_SEPARATOR, cmd);
768 if (!ProgramExists(name)) return 0;
769 real = JLI_MemAlloc(PATH_MAX + 2);
770 if (!realpath(name, real))
771 JLI_StrCpy(real, name);
772 return real;
773}
774
775
776/*
777 * Find a path for the executable
778 */
779static char *
780FindExecName(char *program)
781{
782 char cwdbuf[PATH_MAX+2];
783 char *path;
784 char *tmp_path;
785 char *f;
786 char *result = NULL;
787
788 /* absolute path? */
789 if (*program == FILE_SEPARATOR ||
790 (FILE_SEPARATOR=='\\' && JLI_StrRChr(program, ':')))
791 return Resolve("", program+1);
792
793 /* relative path? */
794 if (JLI_StrRChr(program, FILE_SEPARATOR) != 0) {
795 char buf[PATH_MAX+2];
796 return Resolve(getcwd(cwdbuf, sizeof(cwdbuf)), program);
797 }
798
799 /* from search path? */
800 path = getenv("PATH");
801 if (!path || !*path) path = ".";
802 tmp_path = JLI_MemAlloc(JLI_StrLen(path) + 2);
803 JLI_StrCpy(tmp_path, path);
804
805 for (f=tmp_path; *f && result==0; ) {
806 char *s = f;
807 while (*f && (*f != PATH_SEPARATOR)) ++f;
808 if (*f) *f++ = 0;
809 if (*s == FILE_SEPARATOR)
810 result = Resolve(s, program);
811 else {
812 /* relative path element */
813 char dir[2*PATH_MAX];
814 sprintf(dir, "%s%c%s", getcwd(cwdbuf, sizeof(cwdbuf)),
815 FILE_SEPARATOR, s);
816 result = Resolve(dir, program);
817 }
818 if (result != 0) break;
819 }
820
821 JLI_MemFree(tmp_path);
822 return result;
823}
824
825
826
827/*
828 * Compute the name of the executable
829 *
830 * In order to re-exec securely we need the absolute path of the
831 * executable. On Solaris getexecname(3c) may not return an absolute
832 * path so we use dladdr to get the filename of the executable and
833 * then use realpath to derive an absolute path. From Solaris 9
834 * onwards the filename returned in DL_info structure from dladdr is
835 * an absolute pathname so technically realpath isn't required.
836 * On Linux we read the executable name from /proc/self/exe.
837 * As a fallback, and for platforms other than Solaris and Linux,
838 * we use FindExecName to compute the executable name.
839 */
840static const char*
841SetExecname(char **argv)
842{
843 char* exec_path = NULL;
844#if defined(__solaris__)
845 {
846 Dl_info dlinfo;
847 int (*fptr)();
848
849 fptr = (int (*)())dlsym(RTLD_DEFAULT, "main");
850 if (fptr == NULL) {
851 ReportErrorMessage(DLL_ERROR3, dlerror());
852 return JNI_FALSE;
853 }
854
855 if (dladdr((void*)fptr, &dlinfo)) {
856 char *resolved = (char*)JLI_MemAlloc(PATH_MAX+1);
857 if (resolved != NULL) {
858 exec_path = realpath(dlinfo.dli_fname, resolved);
859 if (exec_path == NULL) {
860 JLI_MemFree(resolved);
861 }
862 }
863 }
864 }
865#elif defined(__linux__)
866 {
867 const char* self = "/proc/self/exe";
868 char buf[PATH_MAX+1];
869 int len = readlink(self, buf, PATH_MAX);
870 if (len >= 0) {
871 buf[len] = '\0'; /* readlink doesn't nul terminate */
872 exec_path = JLI_StringDup(buf);
873 }
874 }
875#else /* !__solaris__ && !__linux */
876 {
877 /* Not implemented */
878 }
879#endif
880
881 if (exec_path == NULL) {
882 exec_path = FindExecName(argv[0]);
883 }
884 execname = exec_path;
885 return exec_path;
886}
887
888void ReportErrorMessage(const char* fmt, ...) {
889 va_list vl;
890 va_start(vl, fmt);
891 vfprintf(stderr, fmt, vl);
892 fprintf(stderr, "\n");
893 va_end(vl);
894}
895
896void ReportErrorMessageSys(const char* fmt, ...) {
897 va_list vl;
898 char *emsg;
899
900 /*
901 * TODO: its safer to use strerror_r but is not available on
902 * Solaris 8. Until then....
903 */
904 emsg = strerror(errno);
905 if (emsg != NULL) {
906 fprintf(stderr, "%s\n", emsg);
907 }
908
909 va_start(vl, fmt);
910 vfprintf(stderr, fmt, vl);
911 fprintf(stderr, "\n");
912 va_end(vl);
913}
914
915void ReportExceptionDescription(JNIEnv * env) {
916 (*env)->ExceptionDescribe(env);
917}
918
919/*
920 * Since using the file system as a registry is a bit risky, perform
921 * additional sanity checks on the identified directory to validate
922 * it as a valid jre/sdk.
923 *
924 * Return 0 if the tests fail; otherwise return non-zero (true).
925 *
926 * Note that checking for anything more than the existence of an
927 * executable object at bin/java relative to the path being checked
928 * will break the regression tests.
929 */
930static int
931CheckSanity(char *path, char *dir)
932{
933 char buffer[PATH_MAX];
934
935 if (JLI_StrLen(path) + JLI_StrLen(dir) + 11 > PATH_MAX)
936 return (0); /* Silently reject "impossibly" long paths */
937
938 sprintf(buffer, "%s/%s/bin/java", path, dir);
939 return ((access(buffer, X_OK) == 0) ? 1 : 0);
940}
941
942/*
943 * Determine if there is an acceptable JRE in the directory dirname.
944 * Upon locating the "best" one, return a fully qualified path to
945 * it. "Best" is defined as the most advanced JRE meeting the
946 * constraints contained in the manifest_info. If no JRE in this
947 * directory meets the constraints, return NULL.
948 *
949 * Note that we don't check for errors in reading the directory
950 * (which would be done by checking errno). This is because it
951 * doesn't matter if we get an error reading the directory, or
952 * we just don't find anything interesting in the directory. We
953 * just return NULL in either case.
954 *
955 * The historical names of j2sdk and j2re were changed to jdk and
956 * jre respecively as part of the 1.5 rebranding effort. Since the
957 * former names are legacy on Linux, they must be recognized for
958 * all time. Fortunately, this is a minor cost.
959 */
960static char
961*ProcessDir(manifest_info *info, char *dirname)
962{
963 DIR *dirp;
964 struct dirent *dp;
965 char *best = NULL;
966 int offset;
967 int best_offset = 0;
968 char *ret_str = NULL;
969 char buffer[PATH_MAX];
970
971 if ((dirp = opendir(dirname)) == NULL)
972 return (NULL);
973
974 do {
975 if ((dp = readdir(dirp)) != NULL) {
976 offset = 0;
977 if ((JLI_StrNCmp(dp->d_name, "jre", 3) == 0) ||
978 (JLI_StrNCmp(dp->d_name, "jdk", 3) == 0))
979 offset = 3;
980 else if (JLI_StrNCmp(dp->d_name, "j2re", 4) == 0)
981 offset = 4;
982 else if (JLI_StrNCmp(dp->d_name, "j2sdk", 5) == 0)
983 offset = 5;
984 if (offset > 0) {
985 if ((JLI_AcceptableRelease(dp->d_name + offset,
986 info->jre_version)) && CheckSanity(dirname, dp->d_name))
987 if ((best == NULL) || (JLI_ExactVersionId(
988 dp->d_name + offset, best + best_offset) > 0)) {
989 if (best != NULL)
990 JLI_MemFree(best);
991 best = JLI_StringDup(dp->d_name);
992 best_offset = offset;
993 }
994 }
995 }
996 } while (dp != NULL);
997 (void) closedir(dirp);
998 if (best == NULL)
999 return (NULL);
1000 else {
1001 ret_str = JLI_MemAlloc(JLI_StrLen(dirname) + JLI_StrLen(best) + 2);
1002 sprintf(ret_str, "%s/%s", dirname, best);
1003 JLI_MemFree(best);
1004 return (ret_str);
1005 }
1006}
1007
1008/*
1009 * This is the global entry point. It examines the host for the optimal
1010 * JRE to be used by scanning a set of directories. The set of directories
1011 * is platform dependent and can be overridden by the environment
1012 * variable JAVA_VERSION_PATH.
1013 *
1014 * This routine itself simply determines the set of appropriate
1015 * directories before passing control onto ProcessDir().
1016 */
1017char*
1018LocateJRE(manifest_info* info)
1019{
1020 char *path;
1021 char *home;
1022 char *target = NULL;
1023 char *dp;
1024 char *cp;
1025
1026 /*
1027 * Start by getting JAVA_VERSION_PATH
1028 */
1029 if (info->jre_restrict_search) {
1030 path = JLI_StringDup(system_dir);
1031 } else if ((path = getenv("JAVA_VERSION_PATH")) != NULL) {
1032 path = JLI_StringDup(path);
1033 } else {
1034 if ((home = getenv("HOME")) != NULL) {
1035 path = (char *)JLI_MemAlloc(JLI_StrLen(home) + \
1036 JLI_StrLen(system_dir) + JLI_StrLen(user_dir) + 2);
1037 sprintf(path, "%s%s:%s", home, user_dir, system_dir);
1038 } else {
1039 path = JLI_StringDup(system_dir);
1040 }
1041 }
1042
1043 /*
1044 * Step through each directory on the path. Terminate the scan with
1045 * the first directory with an acceptable JRE.
1046 */
1047 cp = dp = path;
1048 while (dp != NULL) {
1049 cp = JLI_StrChr(dp, (int)':');
1050 if (cp != NULL)
1051 *cp = (char)NULL;
1052 if ((target = ProcessDir(info, dp)) != NULL)
1053 break;
1054 dp = cp;
1055 if (dp != NULL)
1056 dp++;
1057 }
1058 JLI_MemFree(path);
1059 return (target);
1060}
1061
1062/*
1063 * Given a path to a jre to execute, this routine checks if this process
1064 * is indeed that jre. If not, it exec's that jre.
1065 *
1066 * We want to actually check the paths rather than just the version string
1067 * built into the executable, so that given version specification (and
1068 * JAVA_VERSION_PATH) will yield the exact same Java environment, regardless
1069 * of the version of the arbitrary launcher we start with.
1070 */
1071void
1072ExecJRE(char *jre, char **argv)
1073{
1074 char wanted[PATH_MAX];
1075 const char* progname = GetProgramName();
1076
1077 /*
1078 * Resolve the real path to the directory containing the selected JRE.
1079 */
1080 if (realpath(jre, wanted) == NULL) {
1081 ReportErrorMessage(JRE_ERROR9, jre);
1082 exit(1);
1083 }
1084
1085 /*
1086 * Resolve the real path to the currently running launcher.
1087 */
1088 SetExecname(argv);
1089 if (execname == NULL) {
1090 ReportErrorMessage(JRE_ERROR10);
1091 exit(1);
1092 }
1093
1094 /*
1095 * If the path to the selected JRE directory is a match to the initial
1096 * portion of the path to the currently executing JRE, we have a winner!
1097 * If so, just return.
1098 */
1099 if (JLI_StrNCmp(wanted, execname, JLI_StrLen(wanted)) == 0)
1100 return; /* I am the droid you were looking for */
1101
1102
1103 /*
1104 * This should never happen (because of the selection code in SelectJRE),
1105 * but check for "impossibly" long path names just because buffer overruns
1106 * can be so deadly.
1107 */
1108 if (JLI_StrLen(wanted) + JLI_StrLen(progname) + 6 > PATH_MAX) {
1109 ReportErrorMessage(JRE_ERROR11);
1110 exit(1);
1111 }
1112
1113 /*
1114 * Construct the path and exec it.
1115 */
1116 (void)JLI_StrCat(JLI_StrCat(wanted, "/bin/"), progname);
1117 argv[0] = JLI_StringDup(progname);
1118 if (JLI_IsTraceLauncher()) {
1119 int i;
1120 printf("ReExec Command: %s (%s)\n", wanted, argv[0]);
1121 printf("ReExec Args:");
1122 for (i = 1; argv[i] != NULL; i++)
1123 printf(" %s", argv[i]);
1124 printf("\n");
1125 }
1126 (void)fflush(stdout);
1127 (void)fflush(stderr);
1128 execv(wanted, argv);
1129 ReportErrorMessageSys(JRE_ERROR12, wanted);
1130 exit(1);
1131}
1132
1133/*
1134 * "Borrowed" from Solaris 10 where the unsetenv() function is being added
1135 * to libc thanks to SUSv3 (Standard Unix Specification, version 3). As
1136 * such, in the fullness of time this will appear in libc on all relevant
1137 * Solaris/Linux platforms and maybe even the Windows platform. At that
1138 * time, this stub can be removed.
1139 *
1140 * This implementation removes the environment locking for multithreaded
1141 * applications. (We don't have access to these mutexes within libc and
1142 * the launcher isn't multithreaded.) Note that what remains is platform
1143 * independent, because it only relies on attributes that a POSIX environment
1144 * defines.
1145 *
1146 * Returns 0 on success, -1 on failure.
1147 *
1148 * Also removed was the setting of errno. The only value of errno set
1149 * was EINVAL ("Invalid Argument").
1150 */
1151
1152/*
1153 * s1(environ) is name=value
1154 * s2(name) is name(not the form of name=value).
1155 * if names match, return value of 1, else return 0
1156 */
1157static int
1158match_noeq(const char *s1, const char *s2)
1159{
1160 while (*s1 == *s2++) {
1161 if (*s1++ == '=')
1162 return (1);
1163 }
1164 if (*s1 == '=' && s2[-1] == '\0')
1165 return (1);
1166 return (0);
1167}
1168
1169/*
1170 * added for SUSv3 standard
1171 *
1172 * Delete entry from environ.
1173 * Do not free() memory! Other threads may be using it.
1174 * Keep it around forever.
1175 */
1176static int
1177borrowed_unsetenv(const char *name)
1178{
1179 long idx; /* index into environ */
1180
1181 if (name == NULL || *name == '\0' ||
1182 JLI_StrChr(name, '=') != NULL) {
1183 return (-1);
1184 }
1185
1186 for (idx = 0; environ[idx] != NULL; idx++) {
1187 if (match_noeq(environ[idx], name))
1188 break;
1189 }
1190 if (environ[idx] == NULL) {
1191 /* name not found but still a success */
1192 return (0);
1193 }
1194 /* squeeze up one entry */
1195 do {
1196 environ[idx] = environ[idx+1];
1197 } while (environ[++idx] != NULL);
1198
1199 return (0);
1200}
1201/* --- End of "borrowed" code --- */
1202
1203/*
1204 * Wrapper for unsetenv() function.
1205 */
1206int
1207UnsetEnv(char *name)
1208{
1209 return(borrowed_unsetenv(name));
1210}
1211
1212/* --- Splash Screen shared library support --- */
1213
1214static const char* SPLASHSCREEN_SO = "libsplashscreen.so";
1215
1216static void* hSplashLib = NULL;
1217
1218void* SplashProcAddress(const char* name) {
1219 if (!hSplashLib) {
1220 hSplashLib = dlopen(SPLASHSCREEN_SO, RTLD_LAZY | RTLD_GLOBAL);
1221 }
1222 if (hSplashLib) {
1223 void* sym = dlsym(hSplashLib, name);
1224 return sym;
1225 } else {
1226 return NULL;
1227 }
1228}
1229
1230void SplashFreeLibrary() {
1231 if (hSplashLib) {
1232 dlclose(hSplashLib);
1233 hSplashLib = NULL;
1234 }
1235}
1236
1237const char *
1238jlong_format_specifier() {
1239 return "%lld";
1240}
1241
1242
1243
1244/*
1245 * Block current thread and continue execution in a new thread
1246 */
1247int
1248ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void * args) {
1249 int rslt;
1250#ifdef __linux__
1251 pthread_t tid;
1252 pthread_attr_t attr;
1253 pthread_attr_init(&attr);
1254 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1255
1256 if (stack_size > 0) {
1257 pthread_attr_setstacksize(&attr, stack_size);
1258 }
1259
1260 if (pthread_create(&tid, &attr, (void *(*)(void*))continuation, (void*)args) == 0) {
1261 void * tmp;
1262 pthread_join(tid, &tmp);
1263 rslt = (int)tmp;
1264 } else {
1265 /*
1266 * Continue execution in current thread if for some reason (e.g. out of
1267 * memory/LWP) a new thread can't be created. This will likely fail
1268 * later in continuation as JNI_CreateJavaVM needs to create quite a
1269 * few new threads, anyway, just give it a try..
1270 */
1271 rslt = continuation(args);
1272 }
1273
1274 pthread_attr_destroy(&attr);
1275#else
1276 thread_t tid;
1277 long flags = 0;
1278 if (thr_create(NULL, stack_size, (void *(*)(void *))continuation, args, flags, &tid) == 0) {
1279 void * tmp;
1280 thr_join(tid, NULL, &tmp);
1281 rslt = (int)tmp;
1282 } else {
1283 /* See above. Continue in current thread if thr_create() failed */
1284 rslt = continuation(args);
1285 }
1286#endif
1287 return rslt;
1288}
1289
1290/* Coarse estimation of number of digits assuming the worst case is a 64-bit pid. */
1291#define MAX_PID_STR_SZ 20
1292
1293void SetJavaLauncherPlatformProps() {
1294 /* Linux only */
1295#ifdef __linux__
1296 const char *substr = "-Dsun.java.launcher.pid=";
1297 char *pid_prop_str = (char *)JLI_MemAlloc(JLI_StrLen(substr) + MAX_PID_STR_SZ + 1);
1298 sprintf(pid_prop_str, "%s%d", substr, getpid());
1299 AddOption(pid_prop_str, NULL);
1300#endif
1301}
1302void
1303SetJavaw()
1304{
1305 /* noop on UNIX */
1306 return;
1307}
1308
1309jboolean
1310IsJavaw()
1311{
1312 /* noop on UNIX */
1313 return JNI_FALSE;
1314}