/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#include "jni.h"
#include "jvm.h"
#include "jvm_md.h"
#include "jni_util.h"
#include "io_util.h"
/*
* Platform-specific support for java.lang.Process
*/
#include <assert.h>
#include <stddef.h>
#include <stdlib.h>
#include <ctype.h>
#ifdef _ALLBSD_SOURCE
#else
#include <wait.h>
#endif
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <dirent.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
#ifdef __APPLE__
#include <crt_externs.h>
#endif
/*
* There are 3 possible strategies we might use to "fork":
*
* - fork(2). Very portable and reliable but subject to
* failure due to overcommit (see the documentation on
* /proc/sys/vm/overcommit_memory in Linux proc(5)).
* This is the ancient problem of spurious failure whenever a large
* process starts a small subprocess.
*
* - vfork(). Using this is scary because all relevant man pages
* contain dire warnings, e.g. Linux vfork(2). But at least it's
* documented in the glibc docs and is standardized by XPG4.
* On Linux, one might think that vfork() would be implemented using
* the clone system call with flag CLONE_VFORK, but in fact vfork is
* a separate system call (which is a good sign, suggesting that
* vfork will continue to be supported at least on Linux).
* Another good sign is that glibc implements posix_spawn using
* vfork whenever possible. Note that we cannot use posix_spawn
* ourselves because there's no reliable way to close all inherited
* file descriptors.
*
* - clone() with flags CLONE_VM but not CLONE_THREAD. clone() is
* Linux-specific, but this ought to work - at least the glibc
* sources contain code to handle different combinations of CLONE_VM
* and CLONE_THREAD. However, when this was implemented, it
* appeared to fail on 32-bit i386 (but not 64-bit x86_64) Linux with
* the simple program
* with:
* # Internal Error (os_linux_x86.cpp:683), pid=19940, tid=2934639536
* # Error: pthread_getattr_np failed with errno = 3 (ESRCH)
* We believe this is a glibc bug, reported here:
* but the glibc maintainers closed it as WONTFIX.
*
* Based on the above analysis, we are currently using vfork() on
* Linux and fork() on other Unix systems, but the code to use clone()
* remains.
*/
#ifndef START_CHILD_USE_CLONE
#ifdef __linux__
#else
#define START_CHILD_USE_CLONE 0
#endif
#endif
/* By default, use vfork() on Linux. */
#ifndef START_CHILD_USE_VFORK
#ifdef __linux__
#else
#define START_CHILD_USE_VFORK 0
#endif
#endif
#include <sched.h>
#else
#endif
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
#endif
#ifndef STDERR_FILENO
#endif
#ifndef SA_NOCLDSTOP
#define SA_NOCLDSTOP 0
#endif
#ifndef SA_RESTART
#define SA_RESTART 0
#endif
/* TODO: Refactor. */
do { \
} while(0)
/* This is one of the rare times it's more portable to declare an
* external symbol explicitly, rather than via a system header.
* The declaration is standardized as part of UNIX98, but there is
* no standard (not even de-facto) header file where the
* declaration is to be found. See:
*
* "All identifiers in this volume of IEEE Std 1003.1-2001, except
* environ, are defined in at least one of the headers" (!)
*/
extern char **environ;
static void
{
/* There is a subtle difference between having the signal handler
* for SIGCHLD be SIG_DFL and SIG_IGN. We cannot obtain process
* termination information for child processes if the signal
* handler is SIG_IGN. It must be SIG_DFL.
*
* We used to set the SIGCHLD handler only on Linux, but it's
* safest to set it unconditionally.
*
* Consider what happens if java's parent process sets the SIGCHLD
* handler to SIG_IGN. Normally signal handlers are inherited by
* children, but SIGCHLD is a controversial case. Solaris appears
* to always reset it to SIG_DFL, but this behavior may be
* non-standard-compliant, and we shouldn't rely on it.
*
* References:
*/
}
static void*
{
if (p == NULL)
return p;
}
/**
* If PATH is not defined, the OS provides some default value.
* Unfortunately, there's no portable way to get this value.
* Fortunately, it's only needed if the child has PATH while we do not.
*/
static const char*
defaultPath(void)
{
#ifdef __solaris__
/* These really are the Solaris defaults! */
#else
#endif
}
static const char*
effectivePath(void)
{
const char *s = getenv("PATH");
return (s != NULL) ? s : defaultPath();
}
static int
countOccurrences(const char *s, char c)
{
int count;
for (count = 0; *s != '\0'; s++)
count += (*s == c);
return count;
}
static const char * const *
{
const char *p, *q;
char **pathv;
int i;
for (q = p; (*q != ':') && (*q != '\0'); q++)
;
if (q == p) /* empty PATH component => "." */
pathv[i] = "./";
else {
if (addSlash)
pathv[i][q - p] = '/';
}
}
return (const char * const *) pathv;
}
/**
* Cached value of JVM's effective PATH.
* (We don't support putenv("PATH=...") in native code)
*/
static const char *parentPath;
/**
* Split, canonicalized version of parentPath
*/
static const char * const *parentPathv;
{
parentPath = effectivePath();
}
#ifndef WIFEXITED
#endif
#ifndef WEXITSTATUS
#endif
#ifndef WIFSIGNALED
#endif
#ifndef WTERMSIG
#endif
/* Block until a child process exits and return its exit code.
Note, can only be called once for any given pid. */
{
/* We used to use waitid() on Solaris, waitpid() on Linux, but
* waitpid() is more standard, so use it on all POSIX platforms. */
int status;
/* Wait for the child process to exit. This returns immediately if
the child has already exited. */
switch (errno) {
case ECHILD: return 0;
case EINTR: break;
default: return -1;
}
}
/*
* The child exited normally; get its exit code.
*/
return WEXITSTATUS(status);
} else if (WIFSIGNALED(status)) {
/* The child exited because of a signal.
* The best value to return is 0x80 + signal number,
* because that is what all Unix shells do, and because
* it allows callers to distinguish between process exit and
* process death by signal.
* Unfortunately, the historical behavior on Solaris is to return
* the signal number, and we preserve this for compatibility. */
#ifdef __solaris__
#else
#endif
} else {
/*
* Unknown exit code; pass it through.
*/
return status;
}
}
static ssize_t
{
return result;
}
static int
{
int err;
return err;
}
static int
{
int err;
return err;
}
static int
{
}
static int
isAsciiDigit(char c)
{
return c >= '0' && c <= '9';
}
#ifdef _ALLBSD_SOURCE
#else
#endif
static int
closeDescriptors(void)
{
/* We're trying to close all file descriptors, but opendir() might
* itself be implemented using a file descriptor, and we certainly
* don't want to close that while it's in use. We assume that if
* opendir() is implemented using a file descriptor, then it uses
* the lowest numbered file descriptor, just like open(). So we
* close a couple explicitly. */
return 0;
/* We use readdir64 instead of readdir to work around Solaris bug
*/
int fd;
}
return 1;
}
static int
{
return -1;
}
return 0;
}
static const char *
{
}
static void
{
}
static void
{
int i;
const char *p;
/* Invariant: p always points to the start of a C string. */
vector[i] = p;
while (*(p++));
}
}
static void
{
char *errmsg;
jstring s;
if (errnum != 0) {
if (strcmp(s, "Unknown error") != 0)
detail = s;
}
/* ASCII Decimal representation uses 2.4 times as many bits as binary. */
if (s != NULL) {
if (x != NULL)
}
}
#ifdef DEBUG_PROCESS
/* Debugging process code is difficult; where to write debug output? */
static void
{
}
#endif /* DEBUG_PROCESS */
/**
* Exec FILE as a traditional Bourne shell script (i.e. one without #!).
* If we could do it over again, we would probably not support such an ancient
* misfeature, but compatibility wins over sanity. The original support for
* this was imported accidentally from execvp().
*/
static void
const char *argv[],
const char *const envp[])
{
/* Use the extra word of space provided for us in argv by caller. */
++end;
}
/**
* Like execve(2), except that in case of ENOEXEC, FILE is assumed to
* be a shell script and the system default shell is invoked to run it.
*/
static void
const char *argv[],
const char *const envp[])
{
/* shared address space; be very careful. */
#else
/* unshared address space; we can mutate environ. */
#endif
}
/**
* 'execvpe' should have been included in the Unix standards,
* and is a GNU extension in glibc 2.10.
*
* JDK_execvpe is identical to execvp, except that the child environment is
* specified via the 3rd argument instead of being inherited from environ.
*/
static void
const char *argv[],
const char *const envp[])
{
return;
}
if (*file == '\0') {
return;
}
} else {
/* We must search PATH (parent's, not child's) */
int sticky_errno = 0;
const char * const * dirs;
continue;
}
/* There are 3 responses to various classes of errno:
* return immediately, continue (especially for ENOENT),
* or continue with "sticky" errno.
*
* From exec(3):
*
* If permission is denied for a file (the attempted
* execve returned EACCES), these functions will continue
* searching the rest of the search path. If no other
* file is found, however, they will return with the
* global variable errno set to EACCES.
*/
switch (errno) {
case EACCES:
/* FALLTHRU */
case ENOENT:
case ENOTDIR:
#ifdef ELOOP
case ELOOP:
#endif
#ifdef ESTALE
case ESTALE:
#endif
#ifdef ENODEV
case ENODEV:
#endif
#ifdef ETIMEDOUT
case ETIMEDOUT:
#endif
break; /* Try other directories in PATH */
default:
return;
}
}
if (sticky_errno != 0)
}
}
/*
* Reads nbyte bytes from file descriptor fd into buf,
* The read operation is retried in case of EINTR or partial reads.
*
* Returns number of bytes read (normally nbyte, but may be less in
* case of EOF). In case of read errors, returns -1 and sets errno.
*/
static ssize_t
{
for (;;) {
if (n == 0) {
} else if (n > 0) {
remaining -= n;
if (remaining <= 0)
return nbyte;
/* We were interrupted in the middle of reading the bytes.
* Unlikely, but possible. */
/* Strange signals like SIGJVM1 are possible at any time.
} else {
return -1;
}
}
}
typedef struct _ChildStuff
{
const char **argv;
const char **envv;
const char *pdir;
void *clone_stack;
#endif
} ChildStuff;
static void
{
}
/**
* Child process after a successful fork() or clone().
* This function must not return, and must be prepared for either all
* of its address space to be shared with its parent, or to be a copy.
* It must not modify global variables such as "environ".
*/
static int
{
/* Close the parent sides of the pipes.
Closing pipe fds here is redundant, since closeDescriptors()
would do it anyways, but a little paranoia is a good thing. */
goto WhyCantJohnnyExec;
/* Give the child sides of the pipes the right fileno's. */
/* Note: it is possible for in[0] == 0 */
STDIN_FILENO) == -1) ||
STDOUT_FILENO) == -1))
goto WhyCantJohnnyExec;
if (p->redirectErrorStream) {
goto WhyCantJohnnyExec;
} else {
STDERR_FILENO) == -1)
goto WhyCantJohnnyExec;
}
goto WhyCantJohnnyExec;
/* close everything */
if (closeDescriptors() == 0) { /* failed, close the old way */
int fd;
goto WhyCantJohnnyExec;
}
/* change to the new working directory */
goto WhyCantJohnnyExec;
goto WhyCantJohnnyExec;
/* We used to go to an awful lot of trouble to predict whether the
* child would fail, but there is no reliable way to predict the
* success of an operation without *trying* it, and there's no way
* to try a chdir or exec in the parent. Instead, all we need is a
* way to communicate any failure back to the parent. Easy; we just
* send the errno back to the parent over a pipe in case of failure.
* The tricky thing is, how do we communicate the *success* of exec?
* We use FD_CLOEXEC together with the fact that a read() on a pipe
* yields EOF when the write ends (we have two of them!) are closed.
*/
{
}
_exit(-1);
return 0; /* Suppress warning "no return value from function" */
}
/**
* Start a child process running function childProcess.
* This function only returns in the parent.
*/
#ifdef __attribute_noinline__ /* See: sys/cdefs.h */
#endif
static pid_t
/*
* See clone(2).
* Instead of worrying about which direction the stack grows, just
* allocate twice as much and start the stack in the middle.
*/
/* errno will be set to ENOMEM */
return -1;
return clone(childProcess,
#else
/*
* We separate the call to vfork into a separate function to make
* very sure to keep stack of child from corrupting stack of parent,
* as suggested by the scary gcc warning:
* warning: variable 'foo' might be clobbered by 'longjmp' or 'vfork'
*/
#else
/*
* From Solaris fork(2): In Solaris 10, a call to fork() is
* identical to a call to fork1(); only the calling thread is
* replicated in the child process. This is the POSIX-specified
* behavior for fork().
*/
#endif
if (resultPid == 0)
childProcess(c);
return resultPid;
#endif /* ! START_CHILD_USE_CLONE */
}
{
int errnum;
ChildStuff *c;
c->clone_stack = NULL;
#endif
/* Convert prog + argBlock into a char ** argv.
* Add one word room for expansion of argv for use by
* execve_as_traditional_shell_script.
*/
/* Convert envBlock into a char ** envv */
}
}
goto Catch;
}
resultPid = startChild(c);
if (resultPid < 0) {
goto Catch;
}
case 0: break; /* Exec succeeded */
case sizeof(errnum):
goto Catch;
default:
goto Catch;
}
free(c->clone_stack);
#endif
/* Always clean up the child's side of the pipes */
closeSafely(in [0]);
/* Always clean up fail descriptors */
closeSafely(fail[0]);
free(c);
return resultPid;
/* Clean up the parent's side of the pipes in case of failure only */
closeSafely(out[0]);
closeSafely(err[0]);
goto Finally;
}
{
}