src/solaris/native/java/lang/UNIXProcess_md.c
Print this page
@@ -46,11 +46,19 @@
#include <errno.h>
#include <dirent.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
+#include "processutil_md.h"
+#ifdef __solaris__
+
+#include <spawn.h>
+#include <sys/stat.h>
+
+#endif
+
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
@@ -69,10 +77,14 @@
#define SA_RESTART 0
#endif
#define FAIL_FILENO (STDERR_FILENO + 1)
+extern int jlup_isAsciiDigit(char c);
+
+extern void jlup_moveDescriptor(int fd_from, int fd_to);
+
static void
setSIGCHLDHandler(JNIEnv *env)
{
/* There is a subtle difference between having the signal handler
* for SIGCHLD be SIG_DFL and SIG_IGN. We cannot obtain process
@@ -98,102 +110,27 @@
sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) < 0)
JNU_ThrowInternalError(env, "Can't set SIGCHLD handler");
}
-static void*
-xmalloc(JNIEnv *env, size_t size)
+void*
+jlup_xmalloc(void *env, int size)
{
void *p = malloc(size);
if (p == NULL)
- JNU_ThrowOutOfMemoryError(env, NULL);
+ JNU_ThrowOutOfMemoryError((JNIEnv *)env, NULL);
return p;
}
-#define NEW(type, n) ((type *) xmalloc(env, (n) * sizeof(type)))
-
-/**
- * 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! */
- return (geteuid() == 0 || getuid() == 0) ?
- "/usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin:/usr/sbin" :
- "/usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin:";
-#else
- return ":/bin:/usr/bin"; /* glibc */
-#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 *
-splitPath(JNIEnv *env, const char *path)
-{
- const char *p, *q;
- char **pathv;
- int i;
- int count = countOccurrences(path, ':') + 1;
-
- pathv = NEW(char*, count+1);
- pathv[count] = NULL;
- for (p = path, i = 0; i < count; i++, p = q + 1) {
- for (q = p; (*q != ':') && (*q != '\0'); q++)
- ;
- if (q == p) /* empty PATH component => "." */
- pathv[i] = "./";
- else {
- int addSlash = ((*(q - 1)) != '/');
- pathv[i] = NEW(char, q - p + addSlash + 1);
- memcpy(pathv[i], p, q - p);
- if (addSlash)
- pathv[i][q - p] = '/';
- pathv[i][q - p + addSlash] = '\0';
- }
- }
- 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;
-
static jfieldID field_exitcode;
JNIEXPORT void JNICALL
Java_java_lang_UNIXProcess_initIDs(JNIEnv *env, jclass clazz)
{
field_exitcode = (*env)->GetFieldID(env, clazz, "exitcode", "I");
- parentPath = effectivePath();
- parentPathv = splitPath(env, parentPath);
+ jlup_initialize(env);
setSIGCHLDHandler(env);
}
@@ -257,63 +194,27 @@
*/
return status;
}
}
-static int
-isAsciiDigit(char c)
-{
- return c >= '0' && c <= '9';
-}
-static int
-closeDescriptors(void)
-{
- DIR *dp;
- struct dirent64 *dirp;
- int from_fd = FAIL_FILENO + 1;
+extern int
+jlp_closeDescriptors(int from_fd);
- /* 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. */
-
- close(from_fd); /* for possible use by opendir() */
- close(from_fd + 1); /* another one for good luck */
-
- if ((dp = opendir("/proc/self/fd")) == NULL)
- return 0;
-
- /* We use readdir64 instead of readdir to work around Solaris bug
- * 6395699: /proc/self/fd fails to report file descriptors >= 1024 on Solaris 9
- */
- while ((dirp = readdir64(dp)) != NULL) {
- int fd;
- if (isAsciiDigit(dirp->d_name[0]) &&
- (fd = strtol(dirp->d_name, NULL, 10)) >= from_fd + 2)
- close(fd);
- }
-
- closedir(dp);
-
- return 1;
-}
-
-static void
-moveDescriptor(int fd_from, int fd_to)
+static const char *
+getBytes(JNIEnv *env, jbyteArray arr)
{
- if (fd_from != fd_to) {
- dup2(fd_from, fd_to);
- close(fd_from);
- }
+ return arr == NULL ? NULL :
+ (const char*) (*env)->GetByteArrayElements(env, arr, NULL);
}
static const char *
-getBytes(JNIEnv *env, jbyteArray arr)
+getBytesWithLength(JNIEnv *env, jbyteArray arr, int*len)
{
+ if (len != 0) {
+ *len = (arr == NULL) ? 0 : (*env)->GetArrayLength (env, arr);
+ }
return arr == NULL ? NULL :
(const char*) (*env)->GetByteArrayElements(env, arr, NULL);
}
static void
@@ -322,23 +223,10 @@
if (parr != NULL)
(*env)->ReleaseByteArrayElements(env, arr, (jbyte*) parr, JNI_ABORT);
}
static void
-initVectorFromBlock(const char**vector, const char* block, int count)
-{
- int i;
- const char *p;
- for (i = 0, p = block; i < count; i++) {
- /* Invariant: p always points to the start of a C string. */
- vector[i] = p;
- while (*(p++));
- }
- vector[count] = NULL;
-}
-
-static void
throwIOException(JNIEnv *env, int errnum, const char *defaultDetail)
{
static const char * const format = "error=%d, %s";
const char *detail = defaultDetail;
char *errmsg;
@@ -348,11 +236,11 @@
const char *s = strerror(errnum);
if (strcmp(s, "Unknown error") != 0)
detail = s;
}
/* ASCII Decimal representation uses 2.4 times as many bits as binary. */
- errmsg = NEW(char, strlen(format) + strlen(detail) + 3 * sizeof(errnum));
+ errmsg = jlup_xmalloc(env, strlen(format) + strlen(detail) + 3 * sizeof(errnum));
sprintf(errmsg, format, errnum, detail);
s = JNU_NewStringPlatform(env, errmsg);
if (s != NULL) {
jobject x = JNU_NewObjectByName(env, "java/io/IOException",
"(Ljava/lang/String;)V", s);
@@ -374,154 +262,189 @@
va_end(ap);
fclose(tty);
}
#endif /* DEBUG_PROCESS */
-/* Version of execvpe when child's PATH differs from parent's */
-static int
-execvp_usingParentPath(const char *file, const char *const argv[])
-{
- char expanded_file[PATH_MAX];
- int filelen = strlen(file);
- int sticky_errno = 0;
- const char * const * dirs;
- /* Search parent's PATH */
- for (dirs = parentPathv; *dirs; dirs++) {
- const char * dir = *dirs;
- int dirlen = strlen(dir);
- if (filelen + dirlen + 1 >= PATH_MAX) {
- /* Resist the urge to remove this limit;
- * calling malloc after fork is unsafe. */
- errno = ENAMETOOLONG;
- continue;
- }
- strcpy(expanded_file, dir);
- strcpy(expanded_file + dirlen, file);
- execvp(expanded_file, (char **) argv);
- /* 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:
- sticky_errno = errno;
- /* FALLTHRU */
- case ENOENT:
- case ENOTDIR:
-#ifdef ELOOP
- case ELOOP:
+#ifndef __solaris__
+#undef fork1
+#define fork1() fork()
#endif
-#ifdef ESTALE
- case ESTALE:
-#endif
-#ifdef ENODEV
- case ENODEV:
-#endif
-#ifdef ETIMEDOUT
- case ETIMEDOUT:
-#endif
- break; /* Try other directories in PATH */
- default:
- return -1;
- }
- }
- if (sticky_errno != 0)
- errno = sticky_errno;
- return -1;
-}
-/* execvpe should have been included in the Unix standards. */
-static int
-execvpe(const char *file, const char *const argv[], const char *const envp[])
+#ifdef __solaris__
+
+/* solaris version uses posix_spawn() */
+
+JNIEXPORT jint JNICALL
+Java_java_lang_UNIXProcess_forkAndExec (JNIEnv *env,
+ jobject process,
+ jbyteArray prog,
+ jbyteArray argBlock, jint argc,
+ jbyteArray envBlock, jint envc,
+ jbyteArray dir,
+ jintArray std_fds,
+ jobject helperstr,
+ jboolean redirectErrorStream)
{
- /* 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:
- * http://www.opengroup.org/onlinepubs/009695399/functions/environ.html
- * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_02.html
- *
- * "All identifiers in this volume of IEEE Std 1003.1-2001, except
- * environ, are defined in at least one of the headers" (!)
- */
+ int i, flags, errnum, n, rval, fd = -1;
+ int in[2], out[2], err[2], fail[2], op;
+ int envLength;
+ const char **argv = NULL;
+ const char *pprog = getBytes(env, prog);
+ const char *pargBlock = getBytes(env, argBlock);
+ const char *penvBlock = getBytesWithLength(env, envBlock, &envLength);
+ const char *pdir = getBytes(env, dir);
+ jint *fds = NULL;
+ pid_t targetpid;
+ int hlprcode [2]; /* first response from helper */
extern char **environ;
+ char buf[256], buf1[2];
+ char *ptr;
- if (envp != NULL)
- environ = (char **) envp;
+ const char *helperpath = JNU_GetStringPlatformChars (
+ env, helperstr, JNI_FALSE
+ );
- if (/* Parent and child environment the same? Use child PATH. */
- (envp == NULL)
+ if (helperpath == NULL) {
+ throwIOException(env, errno, "Bad helper path");
+ goto Catch;
+ }
- /* http://www.opengroup.org/onlinepubs/009695399/functions/exec.html
- * "If the file argument contains a slash character, it is used as
- * the pathname for this file. Otherwise, the path prefix for this
- * file is obtained by a search of the directories passed in the
- * PATH environment variable" */
- || (strchr(file, '/') != NULL)
+ in[0] = in[1] = out[0] = out[1] = err[0] = err[1] = fail[0] = fail[1] = -1;
- /* Parent and child PATH the same? Use child PATH. */
- || (strcmp(parentPath, effectivePath()) == 0)
+ assert(prog != NULL && argBlock != NULL);
+ if (pprog == NULL) goto Catch;
+ if (pargBlock == NULL) goto Catch;
+ if (envBlock != NULL && penvBlock == NULL) goto Catch;
+ if (dir != NULL && pdir == NULL) goto Catch;
- /* We want ENOENT, not EACCES, for zero-length program names. */
- || (*file == '\0'))
+ /* Convert pprog + pargBlock into a char ** argv */
+ if ((argv = jlup_xmalloc(env, sizeof(const char *)*( argc + 5))) == NULL)
+ goto Catch;
+ argv[0] = pprog;
+ jlup_initVectorFromBlock(&argv[4], pargBlock, argc);
+ /* new working directory (if any) passed as extra arg */
+ argv[1] = (pdir == NULL) ? "": pdir;
+ /* fd numbers for streams that target will need */
+ argv[2] = buf;
- return execvp(file, (char **) argv);
- else
- return execvp_usingParentPath(file, argv);
-}
+ assert(std_fds != NULL);
+ fds = (*env)->GetIntArrayElements(env, std_fds, NULL);
+ if (fds == NULL) goto Catch;
-static void
-closeSafely(int fd)
-{
- if (fd != -1)
- close(fd);
-}
+ if ((fds[0] == -1 && pipe(in) < 0) ||
+ (fds[1] == -1 && pipe(out) < 0) ||
+ (fds[2] == -1 && pipe(err) < 0) ||
+ (pipe(fail) < 0)) {
+ throwIOException(env, errno, "Bad file descriptor");
+ goto Catch;
+ }
-/*
- * 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.
+
+ /* Two flags passed to child */
+ flags = (err[0] != -1) << 1 ; /* =1 if we created a pipe */
+ flags += redirectErrorStream & 0x1;
+ buf1[0] = '0' + flags;
+ buf1[1] = 0;
+ argv[3] = buf1;
+
+ /* clear FD_CLOEXEC if set. */
+ for (i=0; i<3; i++) {
+ if (fds[i] != -1) {
+ int flags = fcntl(fds[i], F_GETFD);
+ if (flags & FD_CLOEXEC) {
+ fcntl (fds[i], F_SETFD, flags & (~1));
+ }
+ }
+ }
+ /*
+ * we can't move (or close) the descriptors in the parent. We could organise
+ * close and dup2 actions for posix_spawn, but that doesn't work so well
+ * in multi-threaded systems, where other threads could be opening
+ * or closing fds in parallel.
+ * So we pass the actual fd numbers to the helper, and it moves the
+ * them to the right location, and closes all others.
*/
-static ssize_t
-readFully(int fd, void *buf, size_t nbyte)
-{
- ssize_t remaining = nbyte;
- for (;;) {
- ssize_t n = read(fd, buf, remaining);
- if (n == 0) {
- return nbyte - remaining;
- } else if (n > 0) {
- remaining -= n;
- if (remaining <= 0)
- return nbyte;
- /* We were interrupted in the middle of reading the bytes.
- * Unlikely, but possible. */
- buf = (void *) (((char *)buf) + n);
- } else if (errno == EINTR) {
- /* Strange signals like SIGJVM1 are possible at any time.
- * See http://www.dreamsongs.com/WorseIsBetter.html */
+ sprintf (buf, "%d %d %d %d", (in[0]==-1) ? fds[0] : in[0],
+ (out[1]==-1) ? fds[1] : out[1],
+ (err[1]==-1) ? fds[2] : err[1], fail[1]);
+
+ rval = posix_spawn (&targetpid, helperpath, 0, 0, (char * const *) &argv[0], environ);
+ if (rval < 0) {
+ throwIOException(env, errno, "Spawn failed");
+ goto Catch;
+ }
+ close(fail[1]); fail[1] = -1;
+
+ /* need to send the child environment down the pipe. First word
+ * is the number of bytes, followed by the number of entries
+ * in the envrionment, followed by the strings themselves.
+ * In the case where no there is no environment, both words will be -1
+ */
+ if (envBlock == NULL) {
+ envLength = envc = -1;
+ }
+ write (fail[0], &envLength, sizeof(envLength));
+ write (fail[0], &envc, sizeof(envc));
+ if (envLength > 0) {
+ write (fail[0], penvBlock, envLength);
+ }
+
+ n = jlup_readFully(fail[0], &hlprcode[0],sizeof(hlprcode));
+
+ if (n == sizeof(hlprcode)) {
+ /* error */
+ waitpid(targetpid, NULL, 0);
+ if (hlprcode[0] == 1) {
+ throwIOException(env, hlprcode[1], "chdir() failed");
} else {
- return -1;
+ throwIOException(env, hlprcode[1], "exec() failed");
}
+ goto Catch;
+ } else if (n != 0) {
+ throwIOException(env, errno, "Read failed");
+ goto Catch;
}
+
+ /* n==0 => pipe is closed, means successful exec of target */
+
+ Finally:
+ /* If we created pipes, set the parent fds. These fds are returned
+ * to caller to be placed in the relevant FileDescriptor objects
+ */
+ fds[0] = (in [1] != -1) ? in [1] : -1;
+ fds[1] = (out[0] != -1) ? out[0] : -1;
+ fds[2] = (err[0] != -1) ? err[0] : -1;
+
+ /* Always clean up the child's side of the pipes */
+ jlup_closeSafely(in [0]);
+ jlup_closeSafely(out[1]);
+ jlup_closeSafely(err[1]);
+
+ /* Always clean up fail descriptors */
+ jlup_closeSafely(fail[0]);
+
+ free(argv);
+
+ releaseBytes(env, prog, pprog);
+ releaseBytes(env, argBlock, pargBlock);
+ releaseBytes(env, envBlock, penvBlock);
+ releaseBytes(env, dir, pdir);
+
+ if (fds != NULL)
+ (*env)->ReleaseIntArrayElements(env, std_fds, fds, 0);
+
+ return targetpid;
+
+ Catch:
+ /* Clean up the parent's side of the pipes in case of failure only */
+ jlup_closeSafely(in [1]);
+ jlup_closeSafely(out[0]);
+ jlup_closeSafely(err[0]);
+ goto Finally;
}
-#ifndef __solaris__
-#undef fork1
-#define fork1() fork()
-#endif
+#else /* Linux version */
JNIEXPORT jint JNICALL
Java_java_lang_UNIXProcess_forkAndExec(JNIEnv *env,
jobject process,
jbyteArray prog,
@@ -549,20 +472,20 @@
if (pargBlock == NULL) goto Catch;
if (envBlock != NULL && penvBlock == NULL) goto Catch;
if (dir != NULL && pdir == NULL) goto Catch;
/* Convert pprog + pargBlock into a char ** argv */
- if ((argv = NEW(const char *, argc + 2)) == NULL)
+ if ((argv = (const char **)jlup_xmalloc(env, sizeof(const char *)*( argc + 2))) == NULL)
goto Catch;
argv[0] = pprog;
- initVectorFromBlock(argv+1, pargBlock, argc);
+ jlup_initVectorFromBlock(argv+1, pargBlock, argc);
if (envBlock != NULL) {
/* Convert penvBlock into a char ** envv */
- if ((envv = NEW(const char *, envc + 1)) == NULL)
+ if ((envv = (const char **)jlup_xmalloc(env, sizeof(const char *)*( envc + 1))) == NULL)
goto Catch;
- initVectorFromBlock(envv, penvBlock, envc);
+ jlup_initVectorFromBlock(envv, penvBlock, envc);
}
assert(std_fds != NULL);
fds = (*env)->GetIntArrayElements(env, std_fds, NULL);
if (fds == NULL) goto Catch;
@@ -585,31 +508,32 @@
/* Child process */
/* 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. */
- closeSafely(in[1]);
- closeSafely(out[0]);
- closeSafely(err[0]);
- closeSafely(fail[0]);
+ jlup_closeSafely(in[1]);
+ jlup_closeSafely(out[0]);
+ jlup_closeSafely(err[0]);
+ jlup_closeSafely(fail[0]);
/* Give the child sides of the pipes the right fileno's. */
/* Note: it is possible for in[0] == 0 */
- moveDescriptor(in[0] != -1 ? in[0] : fds[0], STDIN_FILENO);
- moveDescriptor(out[1]!= -1 ? out[1] : fds[1], STDOUT_FILENO);
+ jlup_moveDescriptor(in[0] != -1 ? in[0] : fds[0], STDIN_FILENO);
+ jlup_moveDescriptor(out[1]!= -1 ? out[1] : fds[1], STDOUT_FILENO);
if (redirectErrorStream) {
- closeSafely(err[1]);
+ jlup_closeSafely(err[1]);
dup2(STDOUT_FILENO, STDERR_FILENO);
} else {
- moveDescriptor(err[1] != -1 ? err[1] : fds[2], STDERR_FILENO);
+ jlup_moveDescriptor(err[1] != -1 ? err[1] : fds[2], STDERR_FILENO);
}
- moveDescriptor(fail[1], FAIL_FILENO);
+ jlup_moveDescriptor(fail[1], FAIL_FILENO);
/* close everything */
- if (closeDescriptors() == 0) { /* failed, close the old way */
+ if (jlup_closeDescriptors(FAIL_FILENO + 1) == 0) {
+ /* failed, close the old way */
int max_fd = (int)sysconf(_SC_OPEN_MAX);
int i;
for (i = FAIL_FILENO + 1; i < max_fd; i++)
close(i);
}
@@ -619,11 +543,11 @@
goto WhyCantJohnnyExec;
if (fcntl(FAIL_FILENO, F_SETFD, FD_CLOEXEC) == -1)
goto WhyCantJohnnyExec;
- execvpe(argv[0], argv, envv);
+ jlup_execvpe(argv[0], argv, envv);
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
@@ -642,11 +566,11 @@
/* parent process */
close(fail[1]); fail[1] = -1; /* See: WhyCantJohnnyExec */
- switch (readFully(fail[0], &errnum, sizeof(errnum))) {
+ switch (jlup_readFully(fail[0], &errnum, sizeof(errnum))) {
case 0: break; /* Exec succeeded */
case sizeof(errnum):
waitpid(resultPid, NULL, 0);
throwIOException(env, errnum, "Exec failed");
goto Catch;
@@ -659,17 +583,17 @@
fds[1] = (out[0] != -1) ? out[0] : -1;
fds[2] = (err[0] != -1) ? err[0] : -1;
Finally:
/* Always clean up the child's side of the pipes */
- closeSafely(in [0]);
- closeSafely(out[1]);
- closeSafely(err[1]);
+ jlup_closeSafely(in [0]);
+ jlup_closeSafely(out[1]);
+ jlup_closeSafely(err[1]);
/* Always clean up fail descriptors */
- closeSafely(fail[0]);
- closeSafely(fail[1]);
+ jlup_closeSafely(fail[0]);
+ jlup_closeSafely(fail[1]);
free(argv);
free(envv);
releaseBytes(env, prog, pprog);
@@ -682,15 +606,16 @@
return resultPid;
Catch:
/* Clean up the parent's side of the pipes in case of failure only */
- closeSafely(in [1]);
- closeSafely(out[0]);
- closeSafely(err[0]);
+ jlup_closeSafely(in [1]);
+ jlup_closeSafely(out[0]);
+ jlup_closeSafely(err[0]);
goto Finally;
}
+#endif
JNIEXPORT void JNICALL
Java_java_lang_UNIXProcess_destroyProcess(JNIEnv *env, jobject junk, jint pid)
{
kill(pid, SIGTERM);