1 /*
2  * Copyright (c) 1995, 2008, 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 #undef  _LARGEFILE64_SOURCE
27 #define _LARGEFILE64_SOURCE 1
28 
29 #include "jni.h"
30 #include "jvm.h"
31 #include "jvm_md.h"
32 #include "jni_util.h"
33 #include "io_util.h"
34 #include <nativehelper/JNIHelp.h>
35 
36 #define NATIVE_METHOD(className, functionName, signature) \
37 { #functionName, signature, (void*)(className ## _ ## functionName) }
38 
39 /*
40  * Platform-specific support for java.lang.Process
41  */
42 #include <assert.h>
43 #include <stddef.h>
44 #include <stdlib.h>
45 #include <sys/types.h>
46 #include <ctype.h>
47 // Android-changed: Fuchsia: Point to correct location of header. http://b/119426171
48 // #ifdef _ALLBSD_SOURCE
49 #if defined(_ALLBSD_SOURCE) && !defined(__Fuchsia__)
50 #include <wait.h>
51 #else
52 #include <sys/wait.h>
53 #endif
54 #include <signal.h>
55 #include <string.h>
56 #include <errno.h>
57 #include <dirent.h>
58 #include <unistd.h>
59 #include <fcntl.h>
60 #include <limits.h>
61 
62 #ifdef __APPLE__
63 #include <crt_externs.h>
64 #define environ (*_NSGetEnviron())
65 #endif
66 
67 /*
68  * There are 3 possible strategies we might use to "fork":
69  *
70  * - fork(2).  Very portable and reliable but subject to
71  *   failure due to overcommit (see the documentation on
72  *   /proc/sys/vm/overcommit_memory in Linux proc(5)).
73  *   This is the ancient problem of spurious failure whenever a large
74  *   process starts a small subprocess.
75  *
76  * - vfork().  Using this is scary because all relevant man pages
77  *   contain dire warnings, e.g. Linux vfork(2).  But at least it's
78  *   documented in the glibc docs and is standardized by XPG4.
79  *   http://www.opengroup.org/onlinepubs/000095399/functions/vfork.html
80  *   On Linux, one might think that vfork() would be implemented using
81  *   the clone system call with flag CLONE_VFORK, but in fact vfork is
82  *   a separate system call (which is a good sign, suggesting that
83  *   vfork will continue to be supported at least on Linux).
84  *   Another good sign is that glibc implements posix_spawn using
85  *   vfork whenever possible.  Note that we cannot use posix_spawn
86  *   ourselves because there's no reliable way to close all inherited
87  *   file descriptors.
88  *
89  * - clone() with flags CLONE_VM but not CLONE_THREAD.  clone() is
90  *   Linux-specific, but this ought to work - at least the glibc
91  *   sources contain code to handle different combinations of CLONE_VM
92  *   and CLONE_THREAD.  However, when this was implemented, it
93  *   appeared to fail on 32-bit i386 (but not 64-bit x86_64) Linux with
94  *   the simple program
95  *     Runtime.getRuntime().exec("/bin/true").waitFor();
96  *   with:
97  *     #  Internal Error (os_linux_x86.cpp:683), pid=19940, tid=2934639536
98  *     #  Error: pthread_getattr_np failed with errno = 3 (ESRCH)
99  *   We believe this is a glibc bug, reported here:
100  *     http://sources.redhat.com/bugzilla/show_bug.cgi?id=10311
101  *   but the glibc maintainers closed it as WONTFIX.
102  *
103  * Based on the above analysis, we are currently using vfork() on
104  * Linux and fork() on other Unix systems, but the code to use clone()
105  * remains.
106  */
107 
108 #define START_CHILD_USE_CLONE 0  /* clone() currently disabled; see above. */
109 
110 #ifndef START_CHILD_USE_CLONE
111   #ifdef __linux__
112     #define START_CHILD_USE_CLONE 1
113   #else
114     #define START_CHILD_USE_CLONE 0
115   #endif
116 #endif
117 
118 /* By default, use vfork() on Linux. */
119 #ifndef START_CHILD_USE_VFORK
120 // Android-changed: disable vfork under AddressSanitizer.
121 //  #ifdef __linux__
122   #if defined(__linux__) && !__has_feature(address_sanitizer) && \
123       !__has_feature(hwaddress_sanitizer)
124     #define START_CHILD_USE_VFORK 1
125   #else
126     #define START_CHILD_USE_VFORK 0
127   #endif
128 #endif
129 
130 #if START_CHILD_USE_CLONE
131 #include <sched.h>
132 #define START_CHILD_SYSTEM_CALL "clone"
133 #elif START_CHILD_USE_VFORK
134 #define START_CHILD_SYSTEM_CALL "vfork"
135 #else
136 #define START_CHILD_SYSTEM_CALL "fork"
137 #endif
138 
139 #ifndef STDIN_FILENO
140 #define STDIN_FILENO 0
141 #endif
142 
143 #ifndef STDOUT_FILENO
144 #define STDOUT_FILENO 1
145 #endif
146 
147 #ifndef STDERR_FILENO
148 #define STDERR_FILENO 2
149 #endif
150 
151 #ifndef SA_NOCLDSTOP
152 #define SA_NOCLDSTOP 0
153 #endif
154 
155 #ifndef SA_RESTART
156 #define SA_RESTART 0
157 #endif
158 
159 #define FAIL_FILENO (STDERR_FILENO + 1)
160 
161 /* TODO: Refactor. */
162 #define RESTARTABLE(_cmd, _result) do { \
163   do { \
164     (_result) = _cmd; \
165   } while(((_result) == -1) && (errno == EINTR)); \
166 } while(0)
167 
168 /* This is one of the rare times it's more portable to declare an
169  * external symbol explicitly, rather than via a system header.
170  * The declaration is standardized as part of UNIX98, but there is
171  * no standard (not even de-facto) header file where the
172  * declaration is to be found.  See:
173  * http://www.opengroup.org/onlinepubs/009695399/functions/environ.html
174  * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_02.html
175  *
176  * "All identifiers in this volume of IEEE Std 1003.1-2001, except
177  * environ, are defined in at least one of the headers" (!)
178  */
179 extern char **environ;
180 
181 
182 static void
setSIGCHLDHandler(JNIEnv * env)183 setSIGCHLDHandler(JNIEnv *env)
184 {
185     /* There is a subtle difference between having the signal handler
186      * for SIGCHLD be SIG_DFL and SIG_IGN.  We cannot obtain process
187      * termination information for child processes if the signal
188      * handler is SIG_IGN.  It must be SIG_DFL.
189      *
190      * We used to set the SIGCHLD handler only on Linux, but it's
191      * safest to set it unconditionally.
192      *
193      * Consider what happens if java's parent process sets the SIGCHLD
194      * handler to SIG_IGN.  Normally signal handlers are inherited by
195      * children, but SIGCHLD is a controversial case.  Solaris appears
196      * to always reset it to SIG_DFL, but this behavior may be
197      * non-standard-compliant, and we shouldn't rely on it.
198      *
199      * References:
200      * http://www.opengroup.org/onlinepubs/7908799/xsh/exec.html
201      * http://www.pasc.org/interps/unofficial/db/p1003.1/pasc-1003.1-132.html
202      */
203     struct sigaction sa;
204     sa.sa_handler = SIG_DFL;
205     sigemptyset(&sa.sa_mask);
206     sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
207     if (sigaction(SIGCHLD, &sa, NULL) < 0)
208         JNU_ThrowInternalError(env, "Can't set SIGCHLD handler");
209 }
210 
211 static void*
xmalloc(JNIEnv * env,size_t size)212 xmalloc(JNIEnv *env, size_t size)
213 {
214     void *p = malloc(size);
215     if (p == NULL)
216         JNU_ThrowOutOfMemoryError(env, NULL);
217     return p;
218 }
219 
220 #define NEW(type, n) ((type *) xmalloc(env, (n) * sizeof(type)))
221 
222 /**
223  * If PATH is not defined, the OS provides some default value.
224  * Unfortunately, there's no portable way to get this value.
225  * Fortunately, it's only needed if the child has PATH while we do not.
226  */
227 static const char*
defaultPath(void)228 defaultPath(void)
229 {
230 #ifdef __solaris__
231     /* These really are the Solaris defaults! */
232     return (geteuid() == 0 || getuid() == 0) ?
233         "/usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin:/usr/sbin" :
234         "/usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin:";
235 #else
236     return ":/bin:/usr/bin";    /* glibc */
237 #endif
238 }
239 
240 static const char*
effectivePath(void)241 effectivePath(void)
242 {
243     const char *s = getenv("PATH");
244     return (s != NULL) ? s : defaultPath();
245 }
246 
247 static int
countOccurrences(const char * s,char c)248 countOccurrences(const char *s, char c)
249 {
250     int count;
251     for (count = 0; *s != '\0'; s++)
252         count += (*s == c);
253     return count;
254 }
255 
256 static const char * const *
splitPath(JNIEnv * env,const char * path)257 splitPath(JNIEnv *env, const char *path)
258 {
259     const char *p, *q;
260     char **pathv;
261     int i;
262     int count = countOccurrences(path, ':') + 1;
263 
264     pathv = NEW(char*, count+1);
265     pathv[count] = NULL;
266     for (p = path, i = 0; i < count; i++, p = q + 1) {
267         for (q = p; (*q != ':') && (*q != '\0'); q++)
268             ;
269         if (q == p)             /* empty PATH component => "." */
270             pathv[i] = "./";
271         else {
272             int addSlash = ((*(q - 1)) != '/');
273             pathv[i] = NEW(char, q - p + addSlash + 1);
274             memcpy(pathv[i], p, q - p);
275             if (addSlash)
276                 pathv[i][q - p] = '/';
277             pathv[i][q - p + addSlash] = '\0';
278         }
279     }
280     return (const char * const *) pathv;
281 }
282 
283 /**
284  * Cached value of JVM's effective PATH.
285  * (We don't support putenv("PATH=...") in native code)
286  */
287 static const char *parentPath;
288 
289 /**
290  * Split, canonicalized version of parentPath
291  */
292 static const char * const *parentPathv;
293 
294 static jfieldID field_exitcode;
295 
296 JNIEXPORT void JNICALL
UNIXProcess_initIDs(JNIEnv * env,jclass clazz)297 UNIXProcess_initIDs(JNIEnv *env, jclass clazz)
298 {
299     field_exitcode = (*env)->GetFieldID(env, clazz, "exitcode", "I");
300 
301     parentPath  = effectivePath();
302     parentPathv = splitPath(env, parentPath);
303 
304     setSIGCHLDHandler(env);
305 }
306 
307 
308 #ifndef WIFEXITED
309 #define WIFEXITED(status) (((status)&0xFF) == 0)
310 #endif
311 
312 #ifndef WEXITSTATUS
313 #define WEXITSTATUS(status) (((status)>>8)&0xFF)
314 #endif
315 
316 #ifndef WIFSIGNALED
317 #define WIFSIGNALED(status) (((status)&0xFF) > 0 && ((status)&0xFF00) == 0)
318 #endif
319 
320 #ifndef WTERMSIG
321 #define WTERMSIG(status) ((status)&0x7F)
322 #endif
323 
324 /* Block until a child process exits and return its exit code.
325    Note, can only be called once for any given pid. */
326 JNIEXPORT jint JNICALL
UNIXProcess_waitForProcessExit(JNIEnv * env,jobject junk,jint pid)327 UNIXProcess_waitForProcessExit(JNIEnv* env,
328                                               jobject junk,
329                                               jint pid)
330 {
331     /* We used to use waitid() on Solaris, waitpid() on Linux, but
332      * waitpid() is more standard, so use it on all POSIX platforms. */
333     int status;
334     /* Wait for the child process to exit.  This returns immediately if
335        the child has already exited. */
336     while (waitpid(pid, &status, 0) < 0) {
337         switch (errno) {
338         case ECHILD: return 0;
339         case EINTR: break;
340         default: return -1;
341         }
342     }
343 
344     if (WIFEXITED(status)) {
345         /*
346          * The child exited normally; get its exit code.
347          */
348         return WEXITSTATUS(status);
349     } else if (WIFSIGNALED(status)) {
350         /* The child exited because of a signal.
351          * The best value to return is 0x80 + signal number,
352          * because that is what all Unix shells do, and because
353          * it allows callers to distinguish between process exit and
354          * process death by signal.
355          * Unfortunately, the historical behavior on Solaris is to return
356          * the signal number, and we preserve this for compatibility. */
357 #ifdef __solaris__
358         return WTERMSIG(status);
359 #else
360         return 0x80 + WTERMSIG(status);
361 #endif
362     } else {
363         /*
364          * Unknown exit code; pass it through.
365          */
366         return status;
367     }
368 }
369 
370 static ssize_t
restartableWrite(int fd,const void * buf,size_t count)371 restartableWrite(int fd, const void *buf, size_t count)
372 {
373     ssize_t result;
374     RESTARTABLE(write(fd, buf, count), result);
375     return result;
376 }
377 
378 static int
restartableDup2(int fd_from,int fd_to)379 restartableDup2(int fd_from, int fd_to)
380 {
381     int err;
382     RESTARTABLE(dup2(fd_from, fd_to), err);
383     return err;
384 }
385 
386 static int
restartableClose(int fd)387 restartableClose(int fd)
388 {
389     int err;
390     // Android-changed: do not retry EINTR close() failures. b/20501816
391     // Note: This code was removed upstream in OpenJDK 7u50,
392     // commit http://hg.openjdk.java.net/jdk/jdk/rev/e2e5122cd62e
393     // relating to upstream bug JDK-5049299. The entire file was
394     // then dropped in favor of .java code in upstream OpenJDK 9,
395     // commit http://hg.openjdk.java.net/jdk/jdk/rev/fe8344cf6496
396     //
397     // If we integrate OpenJDK 7u50+, this Android patch can be dropped.
398     //
399     // RESTARTABLE(close(fd), err);
400     err = close(fd);
401     return err;
402 }
403 
404 static int
closeSafely(int fd)405 closeSafely(int fd)
406 {
407     return (fd == -1) ? 0 : restartableClose(fd);
408 }
409 
410 static int
isAsciiDigit(char c)411 isAsciiDigit(char c)
412 {
413   return c >= '0' && c <= '9';
414 }
415 
416 // Android-changed: Fuchsia: Alias *64 on Fuchsia builds. http://b/119496969
417 // #ifdef _ALLBSD_SOURCE
418 #if defined(_ALLBSD_SOURCE) || defined(__Fuchsia__)
419 #define FD_DIR "/dev/fd"
420 #define dirent64 dirent
421 #define readdir64 readdir
422 #else
423 #define FD_DIR "/proc/self/fd"
424 #endif
425 
426 static int
closeDescriptors(void)427 closeDescriptors(void)
428 {
429     DIR *dp;
430     struct dirent64 *dirp;
431     int from_fd = FAIL_FILENO + 1;
432 
433     /* We're trying to close all file descriptors, but opendir() might
434      * itself be implemented using a file descriptor, and we certainly
435      * don't want to close that while it's in use.  We assume that if
436      * opendir() is implemented using a file descriptor, then it uses
437      * the lowest numbered file descriptor, just like open().  So we
438      * close a couple explicitly.  */
439 
440     restartableClose(from_fd);          /* for possible use by opendir() */
441     restartableClose(from_fd + 1);      /* another one for good luck */
442 
443     if ((dp = opendir(FD_DIR)) == NULL)
444         return 0;
445 
446     /* We use readdir64 instead of readdir to work around Solaris bug
447      * 6395699: /proc/self/fd fails to report file descriptors >= 1024 on Solaris 9
448      */
449     while ((dirp = readdir64(dp)) != NULL) {
450         int fd;
451         if (isAsciiDigit(dirp->d_name[0]) &&
452             (fd = strtol(dirp->d_name, NULL, 10)) >= from_fd + 2)
453             restartableClose(fd);
454     }
455 
456     closedir(dp);
457 
458     return 1;
459 }
460 
461 static int
moveDescriptor(int fd_from,int fd_to)462 moveDescriptor(int fd_from, int fd_to)
463 {
464     if (fd_from != fd_to) {
465         if ((restartableDup2(fd_from, fd_to) == -1) ||
466             (restartableClose(fd_from) == -1))
467             return -1;
468     }
469     return 0;
470 }
471 
472 static const char *
getBytes(JNIEnv * env,jbyteArray arr)473 getBytes(JNIEnv *env, jbyteArray arr)
474 {
475     return arr == NULL ? NULL :
476         (const char*) (*env)->GetByteArrayElements(env, arr, NULL);
477 }
478 
479 static void
releaseBytes(JNIEnv * env,jbyteArray arr,const char * parr)480 releaseBytes(JNIEnv *env, jbyteArray arr, const char* parr)
481 {
482     if (parr != NULL)
483         (*env)->ReleaseByteArrayElements(env, arr, (jbyte*) parr, JNI_ABORT);
484 }
485 
486 static void
initVectorFromBlock(const char ** vector,const char * block,int count)487 initVectorFromBlock(const char**vector, const char* block, int count)
488 {
489     int i;
490     const char *p;
491     for (i = 0, p = block; i < count; i++) {
492         /* Invariant: p always points to the start of a C string. */
493         vector[i] = p;
494         while (*(p++));
495     }
496     vector[count] = NULL;
497 }
498 
499 static void
throwIOException(JNIEnv * env,int errnum,const char * defaultDetail)500 throwIOException(JNIEnv *env, int errnum, const char *defaultDetail)
501 {
502     static const char * const format = "error=%d, %s";
503     const char *detail = defaultDetail;
504     char *errmsg;
505     jstring s;
506 
507     if (errnum != 0) {
508         const char *s = strerror(errnum);
509         // Android-changed: Fix logic for recognizing error strings. http://b/110019823
510         // if (strcmp(s, "Unknown error") != 0)
511         if (strstr(s, "Unknown error") == 0)
512             detail = s;
513     }
514     /* ASCII Decimal representation uses 2.4 times as many bits as binary. */
515     size_t newsize = strlen(format) + strlen(detail) + 3 * sizeof(errnum);
516     errmsg = NEW(char, newsize);
517     snprintf(errmsg, newsize, format, errnum, detail);
518     s = JNU_NewStringPlatform(env, errmsg);
519     if (s != NULL) {
520         jobject x = JNU_NewObjectByName(env, "java/io/IOException",
521                                         "(Ljava/lang/String;)V", s);
522         if (x != NULL)
523             (*env)->Throw(env, x);
524     }
525     free(errmsg);
526 }
527 
528 #ifdef DEBUG_PROCESS
529 /* Debugging process code is difficult; where to write debug output? */
530 static void
debugPrint(char * format,...)531 debugPrint(char *format, ...)
532 {
533     FILE *tty = fopen("/dev/tty", "w");
534     va_list ap;
535     va_start(ap, format);
536     vfprintf(tty, format, ap);
537     va_end(ap);
538     fclose(tty);
539 }
540 #endif /* DEBUG_PROCESS */
541 
542 /**
543  * Exec FILE as a traditional Bourne shell script (i.e. one without #!).
544  * If we could do it over again, we would probably not support such an ancient
545  * misfeature, but compatibility wins over sanity.  The original support for
546  * this was imported accidentally from execvp().
547  */
548 // Android-added: #if START_CHILD_USE_CLONE || START_CHILD_USE_VFORK
549 #if START_CHILD_USE_CLONE || START_CHILD_USE_VFORK
550 static void
execve_as_traditional_shell_script(const char * file,const char * argv[],const char * const envp[])551 execve_as_traditional_shell_script(const char *file,
552                                    const char *argv[],
553                                    const char *const envp[])
554 {
555     /* Use the extra word of space provided for us in argv by caller. */
556     const char *argv0 = argv[0];
557     const char *const *end = argv;
558     while (*end != NULL)
559         ++end;
560     memmove(argv+2, argv+1, (end-argv) * sizeof (*end));
561     argv[0] = "/bin/sh";
562     argv[1] = file;
563     execve(argv[0], (char **) argv, (char **) envp);
564     /* Can't even exec /bin/sh?  Big trouble, but let's soldier on... */
565     memmove(argv+1, argv+2, (end-argv) * sizeof (*end));
566     argv[0] = argv0;
567 }
568 #endif
569 
570 /**
571  * Like execve(2), except that in case of ENOEXEC, FILE is assumed to
572  * be a shell script and the system default shell is invoked to run it.
573  */
574 static void
execve_with_shell_fallback(const char * file,const char * argv[],const char * const envp[])575 execve_with_shell_fallback(const char *file,
576                            const char *argv[],
577                            const char *const envp[])
578 {
579 #if START_CHILD_USE_CLONE || START_CHILD_USE_VFORK
580     /* shared address space; be very careful. */
581     execve(file, (char **) argv, (char **) envp);
582     if (errno == ENOEXEC)
583         execve_as_traditional_shell_script(file, argv, envp);
584 #else
585     /* unshared address space; we can mutate environ. */
586     environ = (char **) envp;
587     execvp(file, (char **) argv);
588 #endif
589 }
590 
591 /**
592  * 'execvpe' should have been included in the Unix standards,
593  * and is a GNU extension in glibc 2.10.
594  *
595  * JDK_execvpe is identical to execvp, except that the child environment is
596  * specified via the 3rd argument instead of being inherited from environ.
597  */
598 static void
JDK_execvpe(const char * file,const char * argv[],const char * const envp[])599 JDK_execvpe(const char *file,
600             const char *argv[],
601             const char *const envp[])
602 {
603     if (envp == NULL || (char **) envp == environ) {
604         execvp(file, (char **) argv);
605         return;
606     }
607 
608     if (*file == '\0') {
609         errno = ENOENT;
610         return;
611     }
612 
613     if (strchr(file, '/') != NULL) {
614         execve_with_shell_fallback(file, argv, envp);
615     } else {
616         /* We must search PATH (parent's, not child's) */
617         char expanded_file[PATH_MAX];
618         int filelen = strlen(file);
619         int sticky_errno = 0;
620         const char * const * dirs;
621         for (dirs = parentPathv; *dirs; dirs++) {
622             const char * dir = *dirs;
623             int dirlen = strlen(dir);
624             if (filelen + dirlen + 1 >= PATH_MAX) {
625                 errno = ENAMETOOLONG;
626                 continue;
627             }
628             memcpy(expanded_file, dir, dirlen);
629             memcpy(expanded_file + dirlen, file, filelen);
630             expanded_file[dirlen + filelen] = '\0';
631             execve_with_shell_fallback(expanded_file, argv, envp);
632             /* There are 3 responses to various classes of errno:
633              * return immediately, continue (especially for ENOENT),
634              * or continue with "sticky" errno.
635              *
636              * From exec(3):
637              *
638              * If permission is denied for a file (the attempted
639              * execve returned EACCES), these functions will continue
640              * searching the rest of the search path.  If no other
641              * file is found, however, they will return with the
642              * global variable errno set to EACCES.
643              */
644             switch (errno) {
645             case EACCES:
646                 sticky_errno = errno;
647                 /* FALLTHRU */
648             case ENOENT:
649             case ENOTDIR:
650 #ifdef ELOOP
651             case ELOOP:
652 #endif
653 #ifdef ESTALE
654             case ESTALE:
655 #endif
656 #ifdef ENODEV
657             case ENODEV:
658 #endif
659 #ifdef ETIMEDOUT
660             case ETIMEDOUT:
661 #endif
662                 break; /* Try other directories in PATH */
663             default:
664                 return;
665             }
666         }
667         if (sticky_errno != 0)
668             errno = sticky_errno;
669     }
670 }
671 
672 /*
673  * Reads nbyte bytes from file descriptor fd into buf,
674  * The read operation is retried in case of EINTR or partial reads.
675  *
676  * Returns number of bytes read (normally nbyte, but may be less in
677  * case of EOF).  In case of read errors, returns -1 and sets errno.
678  */
679 static ssize_t
readFully(int fd,void * buf,size_t nbyte)680 readFully(int fd, void *buf, size_t nbyte)
681 {
682     ssize_t remaining = nbyte;
683     for (;;) {
684         ssize_t n = read(fd, buf, remaining);
685         if (n == 0) {
686             return nbyte - remaining;
687         } else if (n > 0) {
688             remaining -= n;
689             if (remaining <= 0)
690                 return nbyte;
691             /* We were interrupted in the middle of reading the bytes.
692              * Unlikely, but possible. */
693             buf = (void *) (((char *)buf) + n);
694         } else if (errno == EINTR) {
695             /* Strange signals like SIGJVM1 are possible at any time.
696              * See http://www.dreamsongs.com/WorseIsBetter.html */
697         } else {
698             return -1;
699         }
700     }
701 }
702 
703 typedef struct _ChildStuff
704 {
705     int in[2];
706     int out[2];
707     int err[2];
708     int fail[2];
709     int fds[3];
710     const char **argv;
711     const char **envv;
712     const char *pdir;
713     jboolean redirectErrorStream;
714 #if START_CHILD_USE_CLONE
715     void *clone_stack;
716 #endif
717 } ChildStuff;
718 
719 static void
copyPipe(int from[2],int to[2])720 copyPipe(int from[2], int to[2])
721 {
722     to[0] = from[0];
723     to[1] = from[1];
724 }
725 
726 /**
727  * Child process after a successful fork() or clone().
728  * This function must not return, and must be prepared for either all
729  * of its address space to be shared with its parent, or to be a copy.
730  * It must not modify global variables such as "environ".
731  */
732 static int
childProcess(void * arg)733 childProcess(void *arg)
734 {
735     const ChildStuff* p = (const ChildStuff*) arg;
736 
737     /* Close the parent sides of the pipes.
738        Closing pipe fds here is redundant, since closeDescriptors()
739        would do it anyways, but a little paranoia is a good thing. */
740     if ((closeSafely(p->in[1])   == -1) ||
741         (closeSafely(p->out[0])  == -1) ||
742         (closeSafely(p->err[0])  == -1) ||
743         (closeSafely(p->fail[0]) == -1))
744         goto WhyCantJohnnyExec;
745 
746     /* Give the child sides of the pipes the right fileno's. */
747     /* Note: it is possible for in[0] == 0 */
748     if ((moveDescriptor(p->in[0] != -1 ?  p->in[0] : p->fds[0],
749                         STDIN_FILENO) == -1) ||
750         (moveDescriptor(p->out[1]!= -1 ? p->out[1] : p->fds[1],
751                         STDOUT_FILENO) == -1))
752         goto WhyCantJohnnyExec;
753 
754     if (p->redirectErrorStream) {
755         if ((closeSafely(p->err[1]) == -1) ||
756             (restartableDup2(STDOUT_FILENO, STDERR_FILENO) == -1))
757             goto WhyCantJohnnyExec;
758     } else {
759         if (moveDescriptor(p->err[1] != -1 ? p->err[1] : p->fds[2],
760                            STDERR_FILENO) == -1)
761             goto WhyCantJohnnyExec;
762     }
763 
764     if (moveDescriptor(p->fail[1], FAIL_FILENO) == -1)
765         goto WhyCantJohnnyExec;
766 
767     /* close everything */
768     if (closeDescriptors() == 0) { /* failed,  close the old way */
769         int max_fd = (int)sysconf(_SC_OPEN_MAX);
770         int fd;
771         for (fd = FAIL_FILENO + 1; fd < max_fd; fd++)
772             if (restartableClose(fd) == -1 && errno != EBADF)
773                 goto WhyCantJohnnyExec;
774     }
775 
776     /* change to the new working directory */
777     if (p->pdir != NULL && chdir(p->pdir) < 0)
778         goto WhyCantJohnnyExec;
779 
780     if (fcntl(FAIL_FILENO, F_SETFD, FD_CLOEXEC) == -1)
781         goto WhyCantJohnnyExec;
782 
783     JDK_execvpe(p->argv[0], p->argv, p->envv);
784 
785  WhyCantJohnnyExec:
786     /* We used to go to an awful lot of trouble to predict whether the
787      * child would fail, but there is no reliable way to predict the
788      * success of an operation without *trying* it, and there's no way
789      * to try a chdir or exec in the parent.  Instead, all we need is a
790      * way to communicate any failure back to the parent.  Easy; we just
791      * send the errno back to the parent over a pipe in case of failure.
792      * The tricky thing is, how do we communicate the *success* of exec?
793      * We use FD_CLOEXEC together with the fact that a read() on a pipe
794      * yields EOF when the write ends (we have two of them!) are closed.
795      */
796     {
797         int errnum = errno;
798         restartableWrite(FAIL_FILENO, &errnum, sizeof(errnum));
799     }
800     restartableClose(FAIL_FILENO);
801     _exit(-1);
802     return 0;  /* Suppress warning "no return value from function" */
803 }
804 
805 /**
806  * Start a child process running function childProcess.
807  * This function only returns in the parent.
808  * We are unusually paranoid; use of clone/vfork is
809  * especially likely to tickle gcc/glibc bugs.
810  */
811 #ifdef __attribute_noinline__  /* See: sys/cdefs.h */
812 __attribute_noinline__
813 #endif
814 static pid_t
startChild(ChildStuff * c)815 startChild(ChildStuff *c) {
816 #if START_CHILD_USE_CLONE
817 #define START_CHILD_CLONE_STACK_SIZE (64 * 1024)
818     /*
819      * See clone(2).
820      * Instead of worrying about which direction the stack grows, just
821      * allocate twice as much and start the stack in the middle.
822      */
823     if ((c->clone_stack = malloc(2 * START_CHILD_CLONE_STACK_SIZE)) == NULL)
824         /* errno will be set to ENOMEM */
825         return -1;
826     return clone(childProcess,
827                  c->clone_stack + START_CHILD_CLONE_STACK_SIZE,
828                  CLONE_VFORK | CLONE_VM | SIGCHLD, c);
829 #else
830   #if START_CHILD_USE_VFORK
831     /*
832      * We separate the call to vfork into a separate function to make
833      * very sure to keep stack of child from corrupting stack of parent,
834      * as suggested by the scary gcc warning:
835      *  warning: variable 'foo' might be clobbered by 'longjmp' or 'vfork'
836      */
837     volatile pid_t resultPid = vfork();
838   #else
839     /*
840      * From Solaris fork(2): In Solaris 10, a call to fork() is
841      * identical to a call to fork1(); only the calling thread is
842      * replicated in the child process. This is the POSIX-specified
843      * behavior for fork().
844      */
845     pid_t resultPid = fork();
846   #endif
847     if (resultPid == 0)
848         childProcess(c);
849     assert(resultPid != 0);  /* childProcess never returns */
850     return resultPid;
851 #endif /* ! START_CHILD_USE_CLONE */
852 }
853 
854 JNIEXPORT jint JNICALL
UNIXProcess_forkAndExec(JNIEnv * env,jobject process,jbyteArray prog,jbyteArray argBlock,jint argc,jbyteArray envBlock,jint envc,jbyteArray dir,jintArray std_fds,jboolean redirectErrorStream)855 UNIXProcess_forkAndExec(JNIEnv *env,
856                                        jobject process,
857                                        jbyteArray prog,
858                                        jbyteArray argBlock, jint argc,
859                                        jbyteArray envBlock, jint envc,
860                                        jbyteArray dir,
861                                        jintArray std_fds,
862                                        jboolean redirectErrorStream)
863 {
864     int errnum;
865     int resultPid = -1;
866     int in[2], out[2], err[2], fail[2];
867     jint *fds = NULL;
868     const char *pprog = NULL;
869     const char *pargBlock = NULL;
870     const char *penvBlock = NULL;
871     ChildStuff *c;
872 
873     in[0] = in[1] = out[0] = out[1] = err[0] = err[1] = fail[0] = fail[1] = -1;
874 
875     if ((c = NEW(ChildStuff, 1)) == NULL) return -1;
876     c->argv = NULL;
877     c->envv = NULL;
878     c->pdir = NULL;
879 #if START_CHILD_USE_CLONE
880     c->clone_stack = NULL;
881 #endif
882 
883     /* Convert prog + argBlock into a char ** argv.
884      * Add one word room for expansion of argv for use by
885      * execve_as_traditional_shell_script.
886      */
887     assert(prog != NULL && argBlock != NULL);
888     if ((pprog     = getBytes(env, prog))       == NULL) goto Catch;
889     if ((pargBlock = getBytes(env, argBlock))   == NULL) goto Catch;
890     if ((c->argv = NEW(const char *, argc + 3)) == NULL) goto Catch;
891     c->argv[0] = pprog;
892     initVectorFromBlock(c->argv+1, pargBlock, argc);
893 
894     if (envBlock != NULL) {
895         /* Convert envBlock into a char ** envv */
896         if ((penvBlock = getBytes(env, envBlock))   == NULL) goto Catch;
897         if ((c->envv = NEW(const char *, envc + 1)) == NULL) goto Catch;
898         initVectorFromBlock(c->envv, penvBlock, envc);
899     }
900 
901     if (dir != NULL) {
902         if ((c->pdir = getBytes(env, dir)) == NULL) goto Catch;
903     }
904 
905     assert(std_fds != NULL);
906     fds = (*env)->GetIntArrayElements(env, std_fds, NULL);
907     if (fds == NULL) goto Catch;
908 
909     if ((fds[0] == -1 && pipe(in)  < 0) ||
910         (fds[1] == -1 && pipe(out) < 0) ||
911         (fds[2] == -1 && pipe(err) < 0) ||
912         (pipe(fail) < 0)) {
913         throwIOException(env, errno, "Bad file descriptor");
914         goto Catch;
915     }
916     c->fds[0] = fds[0];
917     c->fds[1] = fds[1];
918     c->fds[2] = fds[2];
919 
920     copyPipe(in,   c->in);
921     copyPipe(out,  c->out);
922     copyPipe(err,  c->err);
923     copyPipe(fail, c->fail);
924 
925     c->redirectErrorStream = redirectErrorStream;
926 
927     resultPid = startChild(c);
928     assert(resultPid != 0);
929 
930     if (resultPid < 0) {
931         throwIOException(env, errno, START_CHILD_SYSTEM_CALL " failed");
932         goto Catch;
933     }
934 
935     restartableClose(fail[1]); fail[1] = -1; /* See: WhyCantJohnnyExec */
936 
937     switch (readFully(fail[0], &errnum, sizeof(errnum))) {
938     case 0: break; /* Exec succeeded */
939     case sizeof(errnum):
940         waitpid(resultPid, NULL, 0);
941         throwIOException(env, errnum, "Exec failed");
942         goto Catch;
943     default:
944         throwIOException(env, errno, "Read failed");
945         goto Catch;
946     }
947 
948     fds[0] = (in [1] != -1) ? in [1] : -1;
949     fds[1] = (out[0] != -1) ? out[0] : -1;
950     fds[2] = (err[0] != -1) ? err[0] : -1;
951 
952  Finally:
953 #if START_CHILD_USE_CLONE
954     free(c->clone_stack);
955 #endif
956 
957     /* Always clean up the child's side of the pipes */
958     closeSafely(in [0]);
959     closeSafely(out[1]);
960     closeSafely(err[1]);
961 
962     /* Always clean up fail descriptors */
963     closeSafely(fail[0]);
964     closeSafely(fail[1]);
965 
966     releaseBytes(env, prog,     pprog);
967     releaseBytes(env, argBlock, pargBlock);
968     releaseBytes(env, envBlock, penvBlock);
969     releaseBytes(env, dir,      c->pdir);
970 
971     free(c->argv);
972     free(c->envv);
973     free(c);
974 
975     if (fds != NULL)
976         (*env)->ReleaseIntArrayElements(env, std_fds, fds, 0);
977 
978     return resultPid;
979 
980  Catch:
981     /* Clean up the parent's side of the pipes in case of failure only */
982     closeSafely(in [1]);
983     closeSafely(out[0]);
984     closeSafely(err[0]);
985     goto Finally;
986 }
987 
988 JNIEXPORT void JNICALL
UNIXProcess_destroyProcess(JNIEnv * env,jobject junk,jint pid)989 UNIXProcess_destroyProcess(JNIEnv *env, jobject junk, jint pid)
990 {
991     kill(pid, SIGTERM);
992 }
993 
994 static JNINativeMethod gMethods[] = {
995   NATIVE_METHOD(UNIXProcess, destroyProcess, "(I)V"),
996   NATIVE_METHOD(UNIXProcess, forkAndExec, "([B[BI[BI[B[IZ)I"),
997   NATIVE_METHOD(UNIXProcess, waitForProcessExit, "(I)I"),
998   NATIVE_METHOD(UNIXProcess, initIDs, "()V"),
999 };
1000 
register_java_lang_UNIXProcess(JNIEnv * env)1001 void register_java_lang_UNIXProcess(JNIEnv* env) {
1002   jniRegisterNativeMethods(env, "java/lang/UNIXProcess", gMethods, NELEM(gMethods));
1003 }
1004