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