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 #ifdef __DragonFly__
39 #include <sys/sysctl.h>
40 #endif
41 #ifdef __FreeBSD__
42 #include <sys/sysctl.h>
43 #include <sys/procctl.h>
44 #ifndef PROC_STACKGAP_DISABLE
45 #define PROC_STACKGAP_DISABLE	0x0002
46 #endif
47 #ifndef PROC_STACKGAP_CTL
48 #define PROC_STACKGAP_CTL	17
49 #endif
50 #endif /* __FreeBSD__ */
51 #include "manifest_info.h"
52 
53 
54 #define JVM_DLL "libjvm.so"
55 #define JAVA_DLL "libjava.so"
56 #ifdef AIX
57 #define LD_LIBRARY_PATH "LIBPATH"
58 #else
59 #define LD_LIBRARY_PATH "LD_LIBRARY_PATH"
60 #endif
61 
62 /* help jettison the LD_LIBRARY_PATH settings in the future */
63 #ifndef SETENV_REQUIRED
64 #define SETENV_REQUIRED
65 #endif
66 
67 #ifdef __solaris__
68 #  include <sys/systeminfo.h>
69 #  include <sys/elf.h>
70 #  include <stdio.h>
71 #endif
72 
73 /*
74  * Flowchart of launcher execs and options processing on unix
75  *
76  * The selection of the proper vm shared library to open depends on
77  * several classes of command line options, including vm "flavor"
78  * options (-client, -server).
79  * The vm selection options are not passed to the running
80  * virtual machine; they must be screened out by the launcher.
81  *
82  * The version specification (if any) is processed first by the
83  * platform independent routine SelectVersion.  This may result in
84  * the exec of the specified launcher version.
85  *
86  * Previously the launcher modified the LD_LIBRARY_PATH appropriately for the
87  * desired data model path, regardless if data models matched or not. The
88  * launcher subsequently exec'ed the desired executable, in order to make the
89  * LD_LIBRARY_PATH path available, for the runtime linker.
90  *
91  * Now, in most cases,the launcher will dlopen the target libjvm.so. All
92  * required libraries are loaded by the runtime linker, using the
93  * $RPATH/$ORIGIN baked into the shared libraries at compile time. Therefore,
94  * in most cases, the launcher will only exec, if the data models are
95  * mismatched, and will not set any environment variables, regardless of the
96  * data models.
97  *
98  * However, if the environment contains a LD_LIBRARY_PATH, this will cause the
99  * launcher to inspect the LD_LIBRARY_PATH. The launcher will check
100  *  a. if the LD_LIBRARY_PATH's first component is the path to the desired
101  *     libjvm.so
102  *  b. if any other libjvm.so is found in any of the paths.
103  * If case b is true, then the launcher will set the LD_LIBRARY_PATH to the
104  * desired JRE and reexec, in order to propagate the environment.
105  *
106  *  Main
107  *  (incoming argv)
108  *  |
109  * \|/
110  * CreateExecutionEnvironment
111  * (determines desired data model)
112  *  |
113  *  |
114  * \|/
115  *  Have Desired Model ? --> NO --> Exit(with error)
116  *  |
117  *  |
118  * \|/
119  * YES
120  *  |
121  *  |
122  * \|/
123  * CheckJvmType
124  * (removes -client, -server, etc.)
125  *  |
126  *  |
127  * \|/
128  * TranslateDashJArgs...
129  * (Prepare to pass args to vm)
130  *  |
131  *  |
132  * \|/
133  * ParseArguments
134  *   |
135  *   |
136  *  \|/
137  * RequiresSetenv
138  * Is LD_LIBRARY_PATH
139  * and friends set ? --> NO --> Continue
140  *  YES
141  *   |
142  *   |
143  *  \|/
144  * Path is desired JRE ? YES --> Continue
145  *  NO
146  *   |
147  *   |
148  *  \|/
149  * Paths have well known
150  * jvm paths ?       --> NO --> Error/Exit
151  *  YES
152  *   |
153  *   |
154  *  \|/
155  *  Does libjvm.so exist
156  *  in any of them ? --> NO  --> Continue
157  *   YES
158  *   |
159  *   |
160  *  \|/
161  *  Set the LD_LIBRARY_PATH
162  *   |
163  *   |
164  *  \|/
165  * Re-exec
166  *   |
167  *   |
168  *  \|/
169  * Main
170  */
171 
172 /* Store the name of the executable once computed */
173 static char *execname = NULL;
174 
175 /*
176  * execname accessor from other parts of platform dependent logic
177  */
178 const char *
GetExecName()179 GetExecName() {
180     return execname;
181 }
182 
183 #ifdef SETENV_REQUIRED
184 static jboolean
JvmExists(const char * path)185 JvmExists(const char *path) {
186     char tmp[PATH_MAX + 1];
187     struct stat statbuf;
188     JLI_Snprintf(tmp, PATH_MAX, "%s/%s", path, JVM_DLL);
189     if (stat(tmp, &statbuf) == 0) {
190         return JNI_TRUE;
191     }
192     return JNI_FALSE;
193 }
194 /*
195  * contains a lib/{server,client}/libjvm.so ?
196  */
197 static jboolean
ContainsLibJVM(const char * env)198 ContainsLibJVM(const char *env) {
199     /* the usual suspects */
200     char clientPattern[] = "lib/client";
201     char serverPattern[] = "lib/server";
202     char *envpath;
203     char *path;
204     char* save_ptr = NULL;
205     jboolean clientPatternFound;
206     jboolean serverPatternFound;
207 
208     /* fastest path */
209     if (env == NULL) {
210         return JNI_FALSE;
211     }
212 
213     /* to optimize for time, test if any of our usual suspects are present. */
214     clientPatternFound = JLI_StrStr(env, clientPattern) != NULL;
215     serverPatternFound = JLI_StrStr(env, serverPattern) != NULL;
216     if (clientPatternFound == JNI_FALSE && serverPatternFound == JNI_FALSE) {
217         return JNI_FALSE;
218     }
219 
220     /*
221      * we have a suspicious path component, check if it contains a libjvm.so
222      */
223     envpath = JLI_StringDup(env);
224     for (path = strtok_r(envpath, ":", &save_ptr); path != NULL; path = strtok_r(NULL, ":", &save_ptr)) {
225         if (clientPatternFound && JLI_StrStr(path, clientPattern) != NULL) {
226             if (JvmExists(path)) {
227                 JLI_MemFree(envpath);
228                 return JNI_TRUE;
229             }
230         }
231         if (serverPatternFound && JLI_StrStr(path, serverPattern)  != NULL) {
232             if (JvmExists(path)) {
233                 JLI_MemFree(envpath);
234                 return JNI_TRUE;
235             }
236         }
237     }
238     JLI_MemFree(envpath);
239     return JNI_FALSE;
240 }
241 
242 /*
243  * Test whether the environment variable needs to be set, see flowchart.
244  */
245 static jboolean
RequiresSetenv(const char * jvmpath)246 RequiresSetenv(const char *jvmpath) {
247     char jpath[PATH_MAX + 1];
248     char *llp;
249     char *dmllp = NULL;
250     char *p; /* a utility pointer */
251 
252 #ifdef AIX
253     /* We always have to set the LIBPATH on AIX because ld doesn't support $ORIGIN. */
254     return JNI_TRUE;
255 #endif
256 
257     llp = getenv("LD_LIBRARY_PATH");
258 #ifdef __solaris__
259     dmllp = getenv("LD_LIBRARY_PATH_64");
260 #endif /* __solaris__ */
261     /* no environment variable is a good environment variable */
262     if (llp == NULL && dmllp == NULL) {
263         return JNI_FALSE;
264     }
265 #ifdef __linux
266     /*
267      * On linux, if a binary is running as sgid or suid, glibc sets
268      * LD_LIBRARY_PATH to the empty string for security purposes. (In contrast,
269      * on Solaris the LD_LIBRARY_PATH variable for a privileged binary does not
270      * lose its settings; but the dynamic linker does apply more scrutiny to the
271      * path.) The launcher uses the value of LD_LIBRARY_PATH to prevent an exec
272      * loop, here and further downstream. Therefore, if we are running sgid or
273      * suid, this function's setting of LD_LIBRARY_PATH will be ineffective and
274      * we should case a return from the calling function.  Getting the right
275      * libraries will be handled by the RPATH. In reality, this check is
276      * redundant, as the previous check for a non-null LD_LIBRARY_PATH will
277      * return back to the calling function forthwith, it is left here to safe
278      * guard against any changes, in the glibc's existing security policy.
279      */
280     if ((getgid() != getegid()) || (getuid() != geteuid())) {
281         return JNI_FALSE;
282     }
283 #endif /* __linux */
284 
285 #ifdef _BSDONLY_SOURCE
286     /*
287      * The BSD's (except MacOSX which doesn't include this file), also clear
288      * LD_LIBRARY_PATH when a binary is running setuid or setgid.
289      */
290     if (issetugid()) {
291      return JNI_FALSE;
292     }
293 #endif /* _BSDONLY_SOURCE */
294 
295     /*
296      * Prevent recursions. Since LD_LIBRARY_PATH is the one which will be set by
297      * previous versions of the JRE, thus it is the only path that matters here.
298      * So we check to see if the desired JRE is set.
299      */
300     JLI_StrNCpy(jpath, jvmpath, PATH_MAX);
301     p = JLI_StrRChr(jpath, '/');
302     *p = '\0';
303     if (llp != NULL && JLI_StrNCmp(llp, jpath, JLI_StrLen(jpath)) == 0) {
304         return JNI_FALSE;
305     }
306 
307     /* scrutinize all the paths further */
308     if (llp != NULL &&  ContainsLibJVM(llp)) {
309         return JNI_TRUE;
310     }
311     if (dmllp != NULL && ContainsLibJVM(dmllp)) {
312         return JNI_TRUE;
313     }
314     return JNI_FALSE;
315 }
316 #endif /* SETENV_REQUIRED */
317 
318 void
CreateExecutionEnvironment(int * pargc,char *** pargv,char jrepath[],jint so_jrepath,char jvmpath[],jint so_jvmpath,char jvmcfg[],jint so_jvmcfg)319 CreateExecutionEnvironment(int *pargc, char ***pargv,
320                            char jrepath[], jint so_jrepath,
321                            char jvmpath[], jint so_jvmpath,
322                            char jvmcfg[],  jint so_jvmcfg) {
323 
324     char * jvmtype = NULL;
325     int argc = *pargc;
326     char **argv = *pargv;
327 
328 #ifdef SETENV_REQUIRED
329     jboolean mustsetenv = JNI_FALSE;
330     char *runpath = NULL; /* existing effective LD_LIBRARY_PATH setting */
331     char* new_runpath = NULL; /* desired new LD_LIBRARY_PATH string */
332     char* newpath = NULL; /* path on new LD_LIBRARY_PATH */
333     char* lastslash = NULL;
334     char** newenvp = NULL; /* current environment */
335     size_t new_runpath_size;
336 #endif  /* SETENV_REQUIRED */
337 
338     /* Compute/set the name of the executable */
339     SetExecname(*pargv);
340 
341     /* Check to see if the jvmpath exists */
342     /* Find out where the JRE is that we will be using. */
343     if (!GetJREPath(jrepath, so_jrepath, JNI_FALSE)) {
344         JLI_ReportErrorMessage(JRE_ERROR1);
345         exit(2);
346     }
347     JLI_Snprintf(jvmcfg, so_jvmcfg, "%s%slib%sjvm.cfg",
348             jrepath, FILESEP, FILESEP);
349     /* Find the specified JVM type */
350     if (ReadKnownVMs(jvmcfg, JNI_FALSE) < 1) {
351         JLI_ReportErrorMessage(CFG_ERROR7);
352         exit(1);
353     }
354 
355     jvmpath[0] = '\0';
356     jvmtype = CheckJvmType(pargc, pargv, JNI_FALSE);
357     if (JLI_StrCmp(jvmtype, "ERROR") == 0) {
358         JLI_ReportErrorMessage(CFG_ERROR9);
359         exit(4);
360     }
361 
362     if (!GetJVMPath(jrepath, jvmtype, jvmpath, so_jvmpath)) {
363         JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath);
364         exit(4);
365     }
366     /*
367      * we seem to have everything we need, so without further ado
368      * we return back, otherwise proceed to set the environment.
369      */
370 #ifdef SETENV_REQUIRED
371     mustsetenv = RequiresSetenv(jvmpath);
372     JLI_TraceLauncher("mustsetenv: %s\n", mustsetenv ? "TRUE" : "FALSE");
373 
374     if (mustsetenv == JNI_FALSE) {
375         return;
376     }
377 #else
378     return;
379 #endif /* SETENV_REQUIRED */
380 
381 #ifdef SETENV_REQUIRED
382     if (mustsetenv) {
383         /*
384          * We will set the LD_LIBRARY_PATH as follows:
385          *
386          *     o          $JVMPATH (directory portion only)
387          *     o          $JRE/lib
388          *     o          $JRE/../lib
389          *
390          * followed by the user's previous effective LD_LIBRARY_PATH, if
391          * any.
392          */
393 
394         runpath = getenv(LD_LIBRARY_PATH);
395 
396         /* runpath contains current effective LD_LIBRARY_PATH setting */
397         { /* New scope to declare local variable */
398             char *new_jvmpath = JLI_StringDup(jvmpath);
399             new_runpath_size = ((runpath != NULL) ? JLI_StrLen(runpath) : 0) +
400                     2 * JLI_StrLen(jrepath) +
401 #ifdef AIX
402                     /* On AIX we additionally need 'jli' in the path because ld doesn't support $ORIGIN. */
403                     JLI_StrLen(jrepath) + JLI_StrLen("/lib//jli:") +
404 #endif
405                     JLI_StrLen(new_jvmpath) + 52;
406             new_runpath = JLI_MemAlloc(new_runpath_size);
407             newpath = new_runpath + JLI_StrLen(LD_LIBRARY_PATH "=");
408 
409 
410             /*
411              * Create desired LD_LIBRARY_PATH value for target data model.
412              */
413             {
414                 /* remove the name of the .so from the JVM path */
415                 lastslash = JLI_StrRChr(new_jvmpath, '/');
416                 if (lastslash)
417                     *lastslash = '\0';
418 
419                 sprintf(new_runpath, LD_LIBRARY_PATH "="
420                         "%s:"
421                         "%s/lib:"
422 #ifdef AIX
423                         "%s/lib/jli:" /* Needed on AIX because ld doesn't support $ORIGIN. */
424 #endif
425                         "%s/../lib",
426                         new_jvmpath,
427                         jrepath,
428 #ifdef AIX
429                         jrepath,
430 #endif
431                         jrepath
432                         );
433 
434                 JLI_MemFree(new_jvmpath);
435 
436                 /*
437                  * Check to make sure that the prefix of the current path is the
438                  * desired environment variable setting, though the RequiresSetenv
439                  * checks if the desired runpath exists, this logic does a more
440                  * comprehensive check.
441                  */
442                 if (runpath != NULL &&
443                         JLI_StrNCmp(newpath, runpath, JLI_StrLen(newpath)) == 0 &&
444                         (runpath[JLI_StrLen(newpath)] == 0 ||
445                         runpath[JLI_StrLen(newpath)] == ':')) {
446                     JLI_MemFree(new_runpath);
447                     return;
448                 }
449             }
450         }
451 
452         /*
453          * Place the desired environment setting onto the prefix of
454          * LD_LIBRARY_PATH.  Note that this prevents any possible infinite
455          * loop of execv() because we test for the prefix, above.
456          */
457         if (runpath != 0) {
458             /* ensure storage for runpath + colon + NULL */
459             if ((JLI_StrLen(runpath) + 1 + 1) > new_runpath_size) {
460                 JLI_ReportErrorMessageSys(JRE_ERROR11);
461                 exit(1);
462             }
463             JLI_StrCat(new_runpath, ":");
464             JLI_StrCat(new_runpath, runpath);
465         }
466 
467         if (putenv(new_runpath) != 0) {
468             /* problem allocating memory; LD_LIBRARY_PATH not set properly */
469             exit(1);
470         }
471 
472         /*
473          * Unix systems document that they look at LD_LIBRARY_PATH only
474          * once at startup, so we have to re-exec the current executable
475          * to get the changed environment variable to have an effect.
476          */
477 
478         newenvp = environ;
479     }
480 #endif /* SETENV_REQUIRED */
481     {
482         char *newexec = execname;
483         JLI_TraceLauncher("TRACER_MARKER:About to EXEC\n");
484         (void) fflush(stdout);
485         (void) fflush(stderr);
486 #ifdef SETENV_REQUIRED
487         if (mustsetenv) {
488             execve(newexec, argv, newenvp);
489         } else {
490             execv(newexec, argv);
491         }
492 #else /* !SETENV_REQUIRED */
493         execv(newexec, argv);
494 #endif /* SETENV_REQUIRED */
495         JLI_ReportErrorMessageSys(JRE_ERROR4, newexec);
496     }
497     exit(1);
498 }
499 
500 
501 static jboolean
GetJVMPath(const char * jrepath,const char * jvmtype,char * jvmpath,jint jvmpathsize)502 GetJVMPath(const char *jrepath, const char *jvmtype,
503            char *jvmpath, jint jvmpathsize)
504 {
505     struct stat s;
506 
507     if (JLI_StrChr(jvmtype, '/')) {
508         JLI_Snprintf(jvmpath, jvmpathsize, "%s/" JVM_DLL, jvmtype);
509     } else {
510         JLI_Snprintf(jvmpath, jvmpathsize, "%s/lib/%s/" JVM_DLL, jrepath, jvmtype);
511     }
512 
513     JLI_TraceLauncher("Does `%s' exist ... ", jvmpath);
514 
515     if (stat(jvmpath, &s) == 0) {
516         JLI_TraceLauncher("yes.\n");
517         return JNI_TRUE;
518     } else {
519         JLI_TraceLauncher("no.\n");
520         return JNI_FALSE;
521     }
522 }
523 
524 /*
525  * Find path to JRE based on .exe's location or registry settings.
526  */
527 static jboolean
GetJREPath(char * path,jint pathsize,jboolean speculative)528 GetJREPath(char *path, jint pathsize, jboolean speculative)
529 {
530     char libjava[MAXPATHLEN];
531     struct stat s;
532 
533     if (GetApplicationHome(path, pathsize)) {
534         /* Is JRE co-located with the application? */
535         JLI_Snprintf(libjava, sizeof(libjava), "%s/lib/" JAVA_DLL, path);
536         if (access(libjava, F_OK) == 0) {
537             JLI_TraceLauncher("JRE path is %s\n", path);
538             return JNI_TRUE;
539         }
540         /* ensure storage for path + /jre + NULL */
541         if ((JLI_StrLen(path) + 4  + 1) > (size_t) pathsize) {
542             JLI_TraceLauncher("Insufficient space to store JRE path\n");
543             return JNI_FALSE;
544         }
545         /* Does the app ship a private JRE in <apphome>/jre directory? */
546         JLI_Snprintf(libjava, sizeof(libjava), "%s/jre/lib/" JAVA_DLL, path);
547         if (access(libjava, F_OK) == 0) {
548             JLI_StrCat(path, "/jre");
549             JLI_TraceLauncher("JRE path is %s\n", path);
550             return JNI_TRUE;
551         }
552     }
553 
554     if (GetApplicationHomeFromDll(path, pathsize)) {
555         JLI_Snprintf(libjava, sizeof(libjava), "%s/lib/" JAVA_DLL, path);
556         if (stat(libjava, &s) == 0) {
557             JLI_TraceLauncher("JRE path is %s\n", path);
558             return JNI_TRUE;
559         }
560     }
561 
562     if (!speculative)
563       JLI_ReportErrorMessage(JRE_ERROR8 JAVA_DLL);
564     return JNI_FALSE;
565 }
566 
567 jboolean
LoadJavaVM(const char * jvmpath,InvocationFunctions * ifn)568 LoadJavaVM(const char *jvmpath, InvocationFunctions *ifn)
569 {
570     void *libjvm;
571 
572     JLI_TraceLauncher("JVM path is %s\n", jvmpath);
573 
574     libjvm = dlopen(jvmpath, RTLD_NOW + RTLD_GLOBAL);
575     if (libjvm == NULL) {
576 #if defined(__solaris__) && defined(__sparc) && !defined(_LP64) /* i.e. 32-bit sparc */
577       FILE * fp;
578       Elf32_Ehdr elf_head;
579       int count;
580       int location;
581 
582       fp = fopen(jvmpath, "r");
583       if (fp == NULL) {
584         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
585         return JNI_FALSE;
586       }
587 
588       /* read in elf header */
589       count = fread((void*)(&elf_head), sizeof(Elf32_Ehdr), 1, fp);
590       fclose(fp);
591       if (count < 1) {
592         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
593         return JNI_FALSE;
594       }
595 
596       /*
597        * Check for running a server vm (compiled with -xarch=v8plus)
598        * on a stock v8 processor.  In this case, the machine type in
599        * the elf header would not be included the architecture list
600        * provided by the isalist command, which is turn is gotten from
601        * sysinfo.  This case cannot occur on 64-bit hardware and thus
602        * does not have to be checked for in binaries with an LP64 data
603        * model.
604        */
605       if (elf_head.e_machine == EM_SPARC32PLUS) {
606         char buf[257];  /* recommended buffer size from sysinfo man
607                            page */
608         long length;
609         char* location;
610 
611         length = sysinfo(SI_ISALIST, buf, 257);
612         if (length > 0) {
613             location = JLI_StrStr(buf, "sparcv8plus ");
614           if (location == NULL) {
615             JLI_ReportErrorMessage(JVM_ERROR3);
616             return JNI_FALSE;
617           }
618         }
619       }
620 #endif
621         JLI_ReportErrorMessage(DLL_ERROR1, __LINE__);
622         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
623         return JNI_FALSE;
624     }
625 
626     ifn->CreateJavaVM = (CreateJavaVM_t)
627         dlsym(libjvm, "JNI_CreateJavaVM");
628     if (ifn->CreateJavaVM == NULL) {
629         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
630         return JNI_FALSE;
631     }
632 
633     ifn->GetDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs_t)
634         dlsym(libjvm, "JNI_GetDefaultJavaVMInitArgs");
635     if (ifn->GetDefaultJavaVMInitArgs == NULL) {
636         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
637         return JNI_FALSE;
638     }
639 
640     ifn->GetCreatedJavaVMs = (GetCreatedJavaVMs_t)
641         dlsym(libjvm, "JNI_GetCreatedJavaVMs");
642     if (ifn->GetCreatedJavaVMs == NULL) {
643         JLI_ReportErrorMessage(DLL_ERROR2, jvmpath, dlerror());
644         return JNI_FALSE;
645     }
646 
647     return JNI_TRUE;
648 }
649 
650 /*
651  * Compute the name of the executable
652  *
653  * In order to re-exec securely we need the absolute path of the
654  * executable. On Solaris getexecname(3c) may not return an absolute
655  * path so we use dladdr to get the filename of the executable and
656  * then use realpath to derive an absolute path. From Solaris 9
657  * onwards the filename returned in DL_info structure from dladdr is
658  * an absolute pathname so technically realpath isn't required.
659  * On Linux we read the executable name from /proc/self/exe.
660  * On FreeBSD, we get the executable name via sysctl(3).
661  * As a fallback, and for platforms other than Solaris, Linux, and
662  * FreeBSD we use FindExecName to compute the executable name.
663  */
664 const char*
SetExecname(char ** argv)665 SetExecname(char **argv)
666 {
667     char* exec_path = NULL;
668 #if defined(__solaris__)
669     {
670         Dl_info dlinfo;
671         int (*fptr)();
672 
673         fptr = (int (*)())dlsym(RTLD_DEFAULT, "main");
674         if (fptr == NULL) {
675             JLI_ReportErrorMessage(DLL_ERROR3, dlerror());
676             return JNI_FALSE;
677         }
678 
679         if (dladdr((void*)fptr, &dlinfo)) {
680             char *resolved = (char*)JLI_MemAlloc(PATH_MAX+1);
681             if (resolved != NULL) {
682                 exec_path = realpath(dlinfo.dli_fname, resolved);
683                 if (exec_path == NULL) {
684                     JLI_MemFree(resolved);
685                 }
686             }
687         }
688     }
689 #elif defined(__linux__)
690     {
691         const char* self = "/proc/self/exe";
692         char buf[PATH_MAX+1];
693         int len = readlink(self, buf, PATH_MAX);
694         if (len >= 0) {
695             buf[len] = '\0';            /* readlink(2) doesn't NUL terminate */
696             exec_path = JLI_StringDup(buf);
697         }
698     }
699 #elif defined(__FreeBSD__) || defined(__DragonFly__)
700     {
701         char buf[PATH_MAX+1];
702         int name[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
703         size_t len = sizeof(buf);
704         if (sysctl(name, 4, buf, &len, NULL, 0) == 0 && len > 0) {
705             buf[len] = '\0';
706             exec_path = JLI_StringDup(buf);
707         }
708     }
709 #else /* !__solaris__ && !__linux__ && !__FreeBSD__ */
710     {
711         /* Not implemented */
712     }
713 #endif
714 
715     if (exec_path == NULL) {
716         exec_path = FindExecName(argv[0]);
717     }
718     execname = exec_path;
719     return exec_path;
720 }
721 
722 /* --- Splash Screen shared library support --- */
723 static const char* SPLASHSCREEN_SO = JNI_LIB_NAME("splashscreen");
724 static void* hSplashLib = NULL;
725 
SplashProcAddress(const char * name)726 void* SplashProcAddress(const char* name) {
727     if (!hSplashLib) {
728         int ret;
729         char jrePath[MAXPATHLEN];
730         char splashPath[MAXPATHLEN];
731 
732         if (!GetJREPath(jrePath, sizeof(jrePath), JNI_FALSE)) {
733             JLI_ReportErrorMessage(JRE_ERROR1);
734             return NULL;
735         }
736         ret = JLI_Snprintf(splashPath, sizeof(splashPath), "%s/lib/%s",
737                      jrePath, SPLASHSCREEN_SO);
738 
739         if (ret >= (int) sizeof(splashPath)) {
740             JLI_ReportErrorMessage(JRE_ERROR11);
741             return NULL;
742         }
743         if (ret < 0) {
744             JLI_ReportErrorMessage(JRE_ERROR13);
745             return NULL;
746         }
747         hSplashLib = dlopen(splashPath, RTLD_LAZY | RTLD_GLOBAL);
748         JLI_TraceLauncher("Info: loaded %s\n", splashPath);
749     }
750     if (hSplashLib) {
751         void* sym = dlsym(hSplashLib, name);
752         return sym;
753     } else {
754         return NULL;
755     }
756 }
757 
SplashFreeLibrary()758 void SplashFreeLibrary() {
759     if (hSplashLib) {
760         dlclose(hSplashLib);
761         hSplashLib = NULL;
762     }
763 }
764 
765 /*
766  * Signature adapter for pthread_create() or thr_create().
767  */
ThreadJavaMain(void * args)768 static void* ThreadJavaMain(void* args) {
769     return (void*)(intptr_t)JavaMain(args);
770 }
771 
772 /*
773  * Block current thread and continue execution in a new thread.
774  */
775 int
CallJavaMainInNewThread(jlong stack_size,void * args)776 CallJavaMainInNewThread(jlong stack_size, void* args) {
777     int rslt;
778 #ifndef __solaris__
779     pthread_t tid;
780     pthread_attr_t attr;
781     pthread_attr_init(&attr);
782     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
783 
784     if (stack_size > 0) {
785         pthread_attr_setstacksize(&attr, stack_size);
786     }
787     pthread_attr_setguardsize(&attr, 0); // no pthread guard page on java threads
788 
789     if (pthread_create(&tid, &attr, ThreadJavaMain, args) == 0) {
790         void* tmp;
791         pthread_join(tid, &tmp);
792         rslt = (int)(intptr_t)tmp;
793     } else {
794        /*
795         * Continue execution in current thread if for some reason (e.g. out of
796         * memory/LWP)  a new thread can't be created. This will likely fail
797         * later in JavaMain as JNI_CreateJavaVM needs to create quite a
798         * few new threads, anyway, just give it a try..
799         */
800         rslt = JavaMain(args);
801     }
802 
803     pthread_attr_destroy(&attr);
804 #else /* __solaris__ */
805     thread_t tid;
806     long flags = 0;
807     if (thr_create(NULL, stack_size, ThreadJavaMain, args, flags, &tid) == 0) {
808         void* tmp;
809         thr_join(tid, NULL, &tmp);
810         rslt = (int)(intptr_t)tmp;
811     } else {
812         /* See above. Continue in current thread if thr_create() failed */
813         rslt = JavaMain(args);
814     }
815 #endif /* !__solaris__ */
816     return rslt;
817 }
818 
819 /* Coarse estimation of number of digits assuming the worst case is a 64-bit pid. */
820 #define MAX_PID_STR_SZ   20
821 
SetJavaLauncherPlatformProps()822 void SetJavaLauncherPlatformProps() {
823    /* Linux and BSD (execpt MaxOSX) only */
824 #if defined(__linux__) || defined(_BSDONLY_SOURCE)
825     const char *substr = "-Dsun.java.launcher.pid=";
826     char *pid_prop_str = (char *)JLI_MemAlloc(JLI_StrLen(substr) + MAX_PID_STR_SZ + 1);
827     sprintf(pid_prop_str, "%s%d", substr, getpid());
828     AddOption(pid_prop_str, NULL);
829 #endif /* __linux__ || _BSDONLY_SOURCE */
830 }
831 
832 int
JVMInit(InvocationFunctions * ifn,jlong threadStackSize,int argc,char ** argv,int mode,char * what,int ret)833 JVMInit(InvocationFunctions* ifn, jlong threadStackSize,
834         int argc, char **argv,
835         int mode, char *what, int ret)
836 {
837 #ifdef __FreeBSD__
838     /*
839      * Kernel stack guard pages interfere with the JVM's guard pages on the
840      * thread stacks and prevent correct stack overflow detection and the
841      * use of reserved pages to allow critical sections to complete.
842      *
843      * Attempt to disable the kernel stack guard pages here before any threads
844      * are created.
845      */
846     int arg = PROC_STACKGAP_DISABLE;
847     procctl(P_PID, getpid(), PROC_STACKGAP_CTL, &arg);
848 #endif
849     ShowSplashScreen();
850     return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret);
851 }
852 
853 void
PostJVMInit(JNIEnv * env,jclass mainClass,JavaVM * vm)854 PostJVMInit(JNIEnv *env, jclass mainClass, JavaVM *vm)
855 {
856     // stubbed out for windows and *nixes.
857 }
858 
859 void
RegisterThread()860 RegisterThread()
861 {
862     // stubbed out for windows and *nixes.
863 }
864 
865 /*
866  * on unix, we return a false to indicate this option is not applicable
867  */
868 jboolean
ProcessPlatformOption(const char * arg)869 ProcessPlatformOption(const char *arg)
870 {
871     return JNI_FALSE;
872 }
873 
874 #ifndef __solaris__
875 
876 /*
877  * Provide a CounterGet() implementation based on gettimeofday() which
878  * is universally available, even though it may not be 'high resolution'
879  * compared to platforms that provide gethrtime() (like Solaris). It is
880  * also subject to time-of-day changes, but alternatives may not be
881  * known to be available at either build time or run time.
882  */
CounterGet()883 uint64_t CounterGet() {
884     uint64_t result = 0;
885     struct timeval tv;
886     if (gettimeofday(&tv, NULL) != -1) {
887         result = 1000000LL * (uint64_t)tv.tv_sec;
888         result += (uint64_t)tv.tv_usec;
889     }
890     return result;
891 }
892 
893 #endif // !__solaris__
894