/* * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ #undef _LARGEFILE64_SOURCE #define _LARGEFILE64_SOURCE 1 #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 #include #include #include #include #include #include #include #include #include #include #include #include #include "processutil_md.h" #ifdef __solaris__ #include #include #endif #ifndef STDIN_FILENO #define STDIN_FILENO 0 #endif #ifndef STDOUT_FILENO #define STDOUT_FILENO 1 #endif #ifndef STDERR_FILENO #define STDERR_FILENO 2 #endif #ifndef SA_NOCLDSTOP #define SA_NOCLDSTOP 0 #endif #ifndef SA_RESTART #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 * 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: * http://www.opengroup.org/onlinepubs/7908799/xsh/exec.html * http://www.pasc.org/interps/unofficial/db/p1003.1/pasc-1003.1-132.html */ struct sigaction sa; sa.sa_handler = SIG_DFL; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_NOCLDSTOP | SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) < 0) JNU_ThrowInternalError(env, "Can't set SIGCHLD handler"); } void* jlup_xmalloc(void *env, int size) { void *p = malloc(size); if (p == NULL) JNU_ThrowOutOfMemoryError((JNIEnv *)env, NULL); return p; } static jfieldID field_exitcode; JNIEXPORT void JNICALL Java_java_lang_UNIXProcess_initIDs(JNIEnv *env, jclass clazz) { field_exitcode = (*env)->GetFieldID(env, clazz, "exitcode", "I"); jlup_initialize(env); setSIGCHLDHandler(env); } #ifndef WIFEXITED #define WIFEXITED(status) (((status)&0xFF) == 0) #endif #ifndef WEXITSTATUS #define WEXITSTATUS(status) (((status)>>8)&0xFF) #endif #ifndef WIFSIGNALED #define WIFSIGNALED(status) (((status)&0xFF) > 0 && ((status)&0xFF00) == 0) #endif #ifndef WTERMSIG #define WTERMSIG(status) ((status)&0x7F) #endif /* Block until a child process exits and return its exit code. Note, can only be called once for any given pid. */ JNIEXPORT jint JNICALL Java_java_lang_UNIXProcess_waitForProcessExit(JNIEnv* env, jobject junk, jint 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. */ while (waitpid(pid, &status, 0) < 0) { switch (errno) { case ECHILD: return 0; case EINTR: break; default: return -1; } } if (WIFEXITED(status)) { /* * 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__ return WTERMSIG(status); #else return 0x80 + WTERMSIG(status); #endif } else { /* * Unknown exit code; pass it through. */ return status; } } extern int jlp_closeDescriptors(int from_fd); static const char * getBytes(JNIEnv *env, jbyteArray arr) { return arr == NULL ? NULL : (const char*) (*env)->GetByteArrayElements(env, arr, NULL); } static const char * 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 releaseBytes(JNIEnv *env, jbyteArray arr, const char* parr) { if (parr != NULL) (*env)->ReleaseByteArrayElements(env, arr, (jbyte*) parr, JNI_ABORT); } static void throwIOException(JNIEnv *env, int errnum, const char *defaultDetail) { static const char * const format = "error=%d, %s"; const char *detail = defaultDetail; char *errmsg; jstring s; if (errnum != 0) { 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 = 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); if (x != NULL) (*env)->Throw(env, x); } free(errmsg); } #ifdef DEBUG_PROCESS /* Debugging process code is difficult; where to write debug output? */ static void debugPrint(char *format, ...) { FILE *tty = fopen("/dev/tty", "w"); va_list ap; va_start(ap, format); vfprintf(tty, format, ap); va_end(ap); fclose(tty); } #endif /* DEBUG_PROCESS */ #ifndef __solaris__ #undef fork1 #define fork1() fork() #endif #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) { 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; const char *helperpath = JNU_GetStringPlatformChars ( env, helperstr, JNI_FALSE ); if (helperpath == NULL) { throwIOException(env, errno, "Bad helper path"); goto Catch; } in[0] = in[1] = out[0] = out[1] = err[0] = err[1] = fail[0] = fail[1] = -1; 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; /* 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; assert(std_fds != NULL); fds = (*env)->GetIntArrayElements(env, std_fds, NULL); if (fds == NULL) goto Catch; 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; } /* 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. */ 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 { 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; } #else /* Linux version */ 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, jboolean redirectErrorStream) { int errnum; int resultPid = -1; int in[2], out[2], err[2], fail[2]; const char **argv = NULL; const char **envv = NULL; const char *pprog = getBytes(env, prog); const char *pargBlock = getBytes(env, argBlock); const char *penvBlock = getBytes(env, envBlock); const char *pdir = getBytes(env, dir); jint *fds = NULL; in[0] = in[1] = out[0] = out[1] = err[0] = err[1] = fail[0] = fail[1] = -1; 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; /* Convert pprog + pargBlock into a char ** argv */ if ((argv = (const char **)jlup_xmalloc(env, sizeof(const char *)*( argc + 2))) == NULL) goto Catch; argv[0] = pprog; jlup_initVectorFromBlock(argv+1, pargBlock, argc); if (envBlock != NULL) { /* Convert penvBlock into a char ** envv */ if ((envv = (const char **)jlup_xmalloc(env, sizeof(const char *)*( envc + 1))) == NULL) goto Catch; jlup_initVectorFromBlock(envv, penvBlock, envc); } assert(std_fds != NULL); fds = (*env)->GetIntArrayElements(env, std_fds, NULL); if (fds == NULL) goto Catch; 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; } resultPid = fork1(); if (resultPid < 0) { throwIOException(env, errno, "Fork failed"); goto Catch; } if (resultPid == 0) { /* 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. */ 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 */ jlup_moveDescriptor(in[0] != -1 ? in[0] : fds[0], STDIN_FILENO); jlup_moveDescriptor(out[1]!= -1 ? out[1] : fds[1], STDOUT_FILENO); if (redirectErrorStream) { jlup_closeSafely(err[1]); dup2(STDOUT_FILENO, STDERR_FILENO); } else { jlup_moveDescriptor(err[1] != -1 ? err[1] : fds[2], STDERR_FILENO); } jlup_moveDescriptor(fail[1], FAIL_FILENO); /* close everything */ 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); } /* change to the new working directory */ if (pdir != NULL && chdir(pdir) < 0) goto WhyCantJohnnyExec; if (fcntl(FAIL_FILENO, F_SETFD, FD_CLOEXEC) == -1) goto WhyCantJohnnyExec; 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 * 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. */ errnum = errno; write(FAIL_FILENO, &errnum, sizeof(errnum)); close(FAIL_FILENO); _exit(-1); } /* parent process */ close(fail[1]); fail[1] = -1; /* See: WhyCantJohnnyExec */ 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; default: throwIOException(env, errno, "Read failed"); goto Catch; } fds[0] = (in [1] != -1) ? in [1] : -1; 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 */ jlup_closeSafely(in [0]); jlup_closeSafely(out[1]); jlup_closeSafely(err[1]); /* Always clean up fail descriptors */ jlup_closeSafely(fail[0]); jlup_closeSafely(fail[1]); free(argv); free(envv); 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 resultPid; 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; } #endif JNIEXPORT void JNICALL Java_java_lang_UNIXProcess_destroyProcess(JNIEnv *env, jobject junk, jint pid) { kill(pid, SIGTERM); }