1 /* 2 * Copyright (c) 1995, 2012, 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 35 /* 36 * Platform-specific support for java.lang.Process 37 */ 38 #include <assert.h> 39 #include <stddef.h> 40 #include <stdlib.h> 41 #include <sys/types.h> 42 #include <ctype.h> 43 #include <sys/wait.h> 44 #include <signal.h> 45 #include <string.h> 46 47 #if defined(__solaris__) || defined(_ALLBSD_SOURCE) 48 #include <spawn.h> 49 #endif 50 51 #include "childproc.h" 52 53 /* 54 * There are 4 possible strategies we might use to "fork": 55 * 56 * - fork(2). Very portable and reliable but subject to 57 * failure due to overcommit (see the documentation on 58 * /proc/sys/vm/overcommit_memory in Linux proc(5)). 59 * This is the ancient problem of spurious failure whenever a large 60 * process starts a small subprocess. 61 * 62 * - vfork(). Using this is scary because all relevant man pages 63 * contain dire warnings, e.g. Linux vfork(2). But at least it's 64 * documented in the glibc docs and is standardized by XPG4. 65 * http://www.opengroup.org/onlinepubs/000095399/functions/vfork.html 66 * On Linux, one might think that vfork() would be implemented using 67 * the clone system call with flag CLONE_VFORK, but in fact vfork is 68 * a separate system call (which is a good sign, suggesting that 69 * vfork will continue to be supported at least on Linux). 70 * Another good sign is that glibc implements posix_spawn using 71 * vfork whenever possible. Note that we cannot use posix_spawn 72 * ourselves because there's no reliable way to close all inherited 73 * file descriptors. 74 * 75 * - clone() with flags CLONE_VM but not CLONE_THREAD. clone() is 76 * Linux-specific, but this ought to work - at least the glibc 77 * sources contain code to handle different combinations of CLONE_VM 78 * and CLONE_THREAD. However, when this was implemented, it 79 * appeared to fail on 32-bit i386 (but not 64-bit x86_64) Linux with 80 * the simple program 81 * Runtime.getRuntime().exec("/bin/true").waitFor(); 82 * with: 83 * # Internal Error (os_linux_x86.cpp:683), pid=19940, tid=2934639536 84 * # Error: pthread_getattr_np failed with errno = 3 (ESRCH) 85 * We believe this is a glibc bug, reported here: 86 * http://sources.redhat.com/bugzilla/show_bug.cgi?id=10311 87 * but the glibc maintainers closed it as WONTFIX. 88 * 89 * - posix_spawn(). While posix_spawn() is a fairly elaborate and 90 * complicated system call, it can't quite do everything that the old 91 * fork()/exec() combination can do, so the only feasible way to do 92 * this, is to use posix_spawn to launch a new helper executable 93 * "jspawnhelper", which in turn execs the target (after cleaning 94 * up file-descriptors etc.) The end result is the same as before, 95 * a child process linked to the parent in the same way, but it 96 * avoids the problem of duplicating the parent (VM) process 97 * address space temporarily, before launching the target command. 98 * 99 * Based on the above analysis, we are currently using vfork() on 100 * Linux and spawn() on other Unix systems, but the code to use clone() 101 * and fork() remains. 102 */ 103 104 #ifdef __linux__ 105 #include <sched.h> 106 #endif 107 108 #ifndef STDIN_FILENO 109 #define STDIN_FILENO 0 110 #endif 111 112 #ifndef STDOUT_FILENO 113 #define STDOUT_FILENO 1 114 #endif 115 116 #ifndef STDERR_FILENO 117 #define STDERR_FILENO 2 118 #endif 119 120 #ifndef SA_NOCLDSTOP 121 #define SA_NOCLDSTOP 0 122 #endif 123 124 #ifndef SA_RESTART 125 #define SA_RESTART 0 126 #endif 127 128 #define FAIL_FILENO (STDERR_FILENO + 1) 129 130 /* TODO: Refactor. */ 131 #define RESTARTABLE(_cmd, _result) do { \ 132 do { \ 133 _result = _cmd; \ 134 } while((_result == -1) && (errno == EINTR)); \ 135 } while(0) 136 137 static void 138 setSIGCHLDHandler(JNIEnv *env) 139 { 140 /* There is a subtle difference between having the signal handler 141 * for SIGCHLD be SIG_DFL and SIG_IGN. We cannot obtain process 142 * termination information for child processes if the signal 143 * handler is SIG_IGN. It must be SIG_DFL. 144 * 145 * We used to set the SIGCHLD handler only on Linux, but it's 146 * safest to set it unconditionally. 147 * 148 * Consider what happens if java's parent process sets the SIGCHLD 149 * handler to SIG_IGN. Normally signal handlers are inherited by 150 * children, but SIGCHLD is a controversial case. Solaris appears 151 * to always reset it to SIG_DFL, but this behavior may be 152 * non-standard-compliant, and we shouldn't rely on it. 153 * 154 * References: 155 * http://www.opengroup.org/onlinepubs/7908799/xsh/exec.html 156 * http://www.pasc.org/interps/unofficial/db/p1003.1/pasc-1003.1-132.html 157 */ 158 struct sigaction sa; 159 sa.sa_handler = SIG_DFL; 160 sigemptyset(&sa.sa_mask); 161 sa.sa_flags = SA_NOCLDSTOP | SA_RESTART; 162 if (sigaction(SIGCHLD, &sa, NULL) < 0) 163 JNU_ThrowInternalError(env, "Can't set SIGCHLD handler"); 164 } 165 166 static void* 167 xmalloc(JNIEnv *env, size_t size) 168 { 169 void *p = malloc(size); 170 if (p == NULL) 171 JNU_ThrowOutOfMemoryError(env, NULL); 172 return p; 173 } 174 175 #define NEW(type, n) ((type *) xmalloc(env, (n) * sizeof(type))) 176 177 /** 178 * If PATH is not defined, the OS provides some default value. 179 * Unfortunately, there's no portable way to get this value. 180 * Fortunately, it's only needed if the child has PATH while we do not. 181 */ 182 static const char* 183 defaultPath(void) 184 { 185 #ifdef __solaris__ 186 /* These really are the Solaris defaults! */ 187 return (geteuid() == 0 || getuid() == 0) ? 188 "/usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin:/usr/sbin" : 189 "/usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin:"; 190 #else 191 return ":/bin:/usr/bin"; /* glibc */ 192 #endif 193 } 194 195 static const char* 196 effectivePath(void) 197 { 198 const char *s = getenv("PATH"); 199 return (s != NULL) ? s : defaultPath(); 200 } 201 202 static int 203 countOccurrences(const char *s, char c) 204 { 205 int count; 206 for (count = 0; *s != '\0'; s++) 207 count += (*s == c); 208 return count; 209 } 210 211 static const char * const * 212 splitPath(JNIEnv *env, const char *path) 213 { 214 const char *p, *q; 215 char **pathv; 216 int i; 217 int count = countOccurrences(path, ':') + 1; 218 219 pathv = NEW(char*, count+1); 220 pathv[count] = NULL; 221 for (p = path, i = 0; i < count; i++, p = q + 1) { 222 for (q = p; (*q != ':') && (*q != '\0'); q++) 223 ; 224 if (q == p) /* empty PATH component => "." */ 225 pathv[i] = "./"; 226 else { 227 int addSlash = ((*(q - 1)) != '/'); 228 pathv[i] = NEW(char, q - p + addSlash + 1); 229 memcpy(pathv[i], p, q - p); 230 if (addSlash) 231 pathv[i][q - p] = '/'; 232 pathv[i][q - p + addSlash] = '\0'; 233 } 234 } 235 return (const char * const *) pathv; 236 } 237 238 static jfieldID helperfield; 239 240 JNIEXPORT void JNICALL 241 Java_java_lang_UNIXProcess_initIDs(JNIEnv *env, jclass clazz) 242 { 243 helperfield = (*env)->GetStaticFieldID(env, clazz, 244 "helperpath", "Ljava/lang/String;"); 245 parentPath = effectivePath(); 246 parentPathv = splitPath(env, parentPath); 247 248 setSIGCHLDHandler(env); 249 } 250 251 252 #ifndef WIFEXITED 253 #define WIFEXITED(status) (((status)&0xFF) == 0) 254 #endif 255 256 #ifndef WEXITSTATUS 257 #define WEXITSTATUS(status) (((status)>>8)&0xFF) 258 #endif 259 260 #ifndef WIFSIGNALED 261 #define WIFSIGNALED(status) (((status)&0xFF) > 0 && ((status)&0xFF00) == 0) 262 #endif 263 264 #ifndef WTERMSIG 265 #define WTERMSIG(status) ((status)&0x7F) 266 #endif 267 268 /* Block until a child process exits and return its exit code. 269 Note, can only be called once for any given pid. */ 270 JNIEXPORT jint JNICALL 271 Java_java_lang_UNIXProcess_waitForProcessExit(JNIEnv* env, 272 jobject junk, 273 jint pid) 274 { 275 /* We used to use waitid() on Solaris, waitpid() on Linux, but 276 * waitpid() is more standard, so use it on all POSIX platforms. */ 277 int status; 278 279 /* Wait for the child process to exit. This returns immediately if 280 the child has already exited. */ 281 while (waitpid(pid, &status, 0) < 0) { 282 switch (errno) { 283 case ECHILD: return 0; 284 case EINTR: break; 285 default: return -1; 286 } 287 } 288 289 if (WIFEXITED(status)) { 290 /* 291 * The child exited normally; get its exit code. 292 */ 293 return WEXITSTATUS(status); 294 } else if (WIFSIGNALED(status)) { 295 /* The child exited because of a signal. 296 * The best value to return is 0x80 + signal number, 297 * because that is what all Unix shells do, and because 298 * it allows callers to distinguish between process exit and 299 * process death by signal. 300 * Unfortunately, the historical behavior on Solaris is to return 301 * the signal number, and we preserve this for compatibility. */ 302 #ifdef __solaris__ 303 return WTERMSIG(status); 304 #else 305 return 0x80 + WTERMSIG(status); 306 #endif 307 } else { 308 /* 309 * Unknown exit code; pass it through. 310 */ 311 return status; 312 } 313 } 314 315 static const char * 316 getBytes(JNIEnv *env, jbyteArray arr) 317 { 318 return arr == NULL ? NULL : 319 (const char*) (*env)->GetByteArrayElements(env, arr, NULL); 320 } 321 322 static void 323 releaseBytes(JNIEnv *env, jbyteArray arr, const char* parr) 324 { 325 if (parr != NULL) 326 (*env)->ReleaseByteArrayElements(env, arr, (jbyte*) parr, JNI_ABORT); 327 } 328 329 static void 330 throwIOException(JNIEnv *env, int errnum, const char *defaultDetail) 331 { 332 static const char * const format = "error=%d, %s"; 333 const char *detail = defaultDetail; 334 char *errmsg; 335 jstring s; 336 337 if (errnum != 0) { 338 const char *s = strerror(errnum); 339 if (strcmp(s, "Unknown error") != 0) 340 detail = s; 341 } 342 /* ASCII Decimal representation uses 2.4 times as many bits as binary. */ 343 errmsg = NEW(char, strlen(format) + strlen(detail) + 3 * sizeof(errnum)); 344 sprintf(errmsg, format, errnum, detail); 345 s = JNU_NewStringPlatform(env, errmsg); 346 if (s != NULL) { 347 jobject x = JNU_NewObjectByName(env, "java/io/IOException", 348 "(Ljava/lang/String;)V", s); 349 if (x != NULL) 350 (*env)->Throw(env, x); 351 } 352 free(errmsg); 353 } 354 355 #ifdef DEBUG_PROCESS 356 /* Debugging process code is difficult; where to write debug output? */ 357 static void 358 debugPrint(char *format, ...) 359 { 360 FILE *tty = fopen("/dev/tty", "w"); 361 va_list ap; 362 va_start(ap, format); 363 vfprintf(tty, format, ap); 364 va_end(ap); 365 fclose(tty); 366 } 367 #endif /* DEBUG_PROCESS */ 368 369 static void 370 copyPipe(int from[2], int to[2]) 371 { 372 to[0] = from[0]; 373 to[1] = from[1]; 374 } 375 376 /* arg is an array of pointers to 0 terminated strings. array is terminated 377 * by a null element. 378 * 379 * *nelems and *nbytes receive the number of elements of array (incl 0) 380 * and total number of bytes (incl. 0) 381 * Note. An empty array will have one null element 382 * But if arg is null, then *nelems set to 0, and *nbytes to 0 383 */ 384 static void arraysize (const char * const *arg, int *nelems, int *nbytes) 385 { 386 int i, bytes, count; 387 const char * const *a = arg; 388 char *p; 389 int *q; 390 if (arg == 0) { 391 *nelems = 0; 392 *nbytes = 0; 393 return; 394 } 395 /* count the array elements and number of bytes */ 396 for (count=0, bytes=0; *a != 0; count++, a++) { 397 bytes += strlen (*a)+1; 398 } 399 *nbytes = bytes; 400 *nelems = count+1; 401 } 402 403 /* copy the strings from arg[] into buf, starting at given offset 404 * return new offset to next free byte 405 */ 406 static int copystrings (char *buf, int offset, const char * const *arg) { 407 char *p; 408 const char * const *a; 409 int count=0; 410 411 if (arg == 0) { 412 return offset; 413 } 414 for (p=buf+offset, a=arg; *a != 0; a++) { 415 int len = strlen (*a) +1; 416 memcpy (p, *a, len); 417 p += len; 418 count += len; 419 } 420 return offset+count; 421 } 422 423 /** 424 * We are unusually paranoid; use of clone/vfork is 425 * especially likely to tickle gcc/glibc bugs. 426 */ 427 #ifdef __attribute_noinline__ /* See: sys/cdefs.h */ 428 __attribute_noinline__ 429 #endif 430 431 #define START_CHILD_USE_CLONE 0 /* clone() currently disabled; see above. */ 432 433 #ifdef START_CHILD_USE_CLONE 434 static pid_t 435 cloneChild(ChildStuff *c) { 436 #ifdef __linux__ 437 #define START_CHILD_CLONE_STACK_SIZE (64 * 1024) 438 439 /* 440 * See clone(2). 441 * Instead of worrying about which direction the stack grows, just 442 * allocate twice as much and start the stack in the middle. 443 */ 444 if ((c->clone_stack = malloc(2 * START_CHILD_CLONE_STACK_SIZE)) == NULL) 445 /* errno will be set to ENOMEM */ 446 return -1; 447 return clone(childProcess, 448 c->clone_stack + START_CHILD_CLONE_STACK_SIZE, 449 CLONE_VFORK | CLONE_VM | SIGCHLD, c); 450 #else 451 /* not available on Solaris / Mac */ 452 assert(0); 453 return -1; 454 #endif 455 } 456 #endif 457 458 static pid_t 459 vforkChild(ChildStuff *c) { 460 volatile pid_t resultPid; 461 462 /* 463 * We separate the call to vfork into a separate function to make 464 * very sure to keep stack of child from corrupting stack of parent, 465 * as suggested by the scary gcc warning: 466 * warning: variable 'foo' might be clobbered by 'longjmp' or 'vfork' 467 */ 468 resultPid = vfork(); 469 470 if (resultPid == 0) { 471 childProcess(c); 472 } 473 assert(resultPid != 0); /* childProcess never returns */ 474 return resultPid; 475 } 476 477 static pid_t 478 forkChild(ChildStuff *c) { 479 pid_t resultPid; 480 481 /* 482 * From Solaris fork(2): In Solaris 10, a call to fork() is 483 * identical to a call to fork1(); only the calling thread is 484 * replicated in the child process. This is the POSIX-specified 485 * behavior for fork(). 486 */ 487 resultPid = fork(); 488 489 if (resultPid == 0) { 490 childProcess(c); 491 } 492 assert(resultPid != 0); /* childProcess never returns */ 493 return resultPid; 494 } 495 496 static pid_t 497 spawnChild(JNIEnv *env, jobject process, ChildStuff *c) { 498 pid_t resultPid; 499 const char *helperpath; 500 jobject helperobj; 501 jboolean isCopy; 502 int i, offset, rval, bufsize; 503 char *buf, buf1[16]; 504 char *hlpargs[2]; 505 SpawnInfo sp; 506 507 helperobj = (*env)->GetStaticObjectField( 508 env, (*env)->GetObjectClass (env, process), 509 helperfield 510 ); 511 if (helperobj == NULL) { 512 return -1; 513 } 514 helperpath = GetStringPlatformChars (env, helperobj, &isCopy); 515 /* need to tell helper which fd is for receiving the childstuff 516 * and which fd to send response back on 517 */ 518 sprintf (buf1, "%d:%d", c->childenv[0], c->fail[1]); 519 /* put the fd string as argument to the helper cmd */ 520 hlpargs[0] = buf1; 521 hlpargs[1] = 0; 522 523 /* Following items are sent down the pipe to the helper 524 * after it is spawned. 525 * All strings are null terminated. All arrays of strings 526 * have an empty string for termination. 527 * - the ChildStuff struct 528 * - the SpawnInfo struct 529 * - the argv strings array 530 * - the envv strings array 531 * - the home directory string 532 * - the parentPath string 533 * - the parentPathv array 534 */ 535 /* First calculate the sizes */ 536 arraysize (c->argv, &sp.nargv, &sp.argvBytes); 537 bufsize = sp.argvBytes; 538 arraysize (c->envv, &sp.nenvv, &sp.envvBytes); 539 bufsize += sp.envvBytes; 540 sp.dirlen = c->pdir == 0 ? 0 : strlen (c->pdir)+1; 541 bufsize += sp.dirlen; 542 sp.parentPathLen = parentPath == 0 ? 0 : strlen (parentPath)+1; 543 bufsize += sp.parentPathLen; 544 arraysize (parentPathv, &sp.nparentPathv, &sp.parentPathvBytes); 545 bufsize += sp.parentPathvBytes; 546 /* We need to clear FD_CLOEXEC if set in the fds[]. 547 * Files are created FD_CLOEXEC in Java. 548 * Otherwise, they will be closed when the target gets exec'd */ 549 for (i=0; i<3; i++) { 550 if (c->fds[i] != -1) { 551 int flags = fcntl(c->fds[i], F_GETFD); 552 if (flags & FD_CLOEXEC) { 553 fcntl (c->fds[i], F_SETFD, flags & (~1)); 554 } 555 } 556 } 557 558 rval = posix_spawn (&resultPid, helperpath, 0, 0, (char * const *) hlpargs, environ); 559 560 if (rval != 0) { 561 return -1; 562 } 563 564 /* now the lengths are known, copy the data */ 565 buf = NEW (char, bufsize); 566 if (buf == 0) { 567 return -1; 568 } 569 offset = copystrings (buf, 0, &c->argv[0]); 570 offset = copystrings (buf, offset, &c->envv[0]); 571 memcpy (buf+offset, c->pdir, sp.dirlen); 572 offset += sp.dirlen; 573 memcpy (buf+offset, parentPath, sp.parentPathLen); 574 offset += sp.parentPathLen; 575 offset = copystrings (buf, offset, parentPathv); 576 assert (offset == bufsize); 577 578 int magic = magicNumber(); 579 580 /* write the two structs and the data buffer */ 581 write (c->childenv[1], (char *)&magic, sizeof(magic)); // magic number first 582 write (c->childenv[1], (char *)c, sizeof(*c)); 583 write (c->childenv[1], (char *)&sp, sizeof(sp)); 584 write (c->childenv[1], buf, bufsize); 585 free (buf); 586 587 /* In this mode an external main() in invoked which calls back into 588 * childProcess() in this file, rather than directly 589 * via the statement below */ 590 return resultPid; 591 } 592 593 /* 594 * Start a child process running function childProcess. 595 * This function only returns in the parent. 596 */ 597 static pid_t 598 startChild(JNIEnv *env, jobject process, ChildStuff *c) { 599 switch (c->mode) { 600 case MODE_VFORK: 601 return vforkChild(c); 602 break; 603 case MODE_FORK: 604 return forkChild(c); 605 break; 606 case MODE_SPAWN: 607 return spawnChild(env, process, c); 608 } 609 } 610 611 JNIEXPORT jint JNICALL 612 Java_java_lang_UNIXProcess_forkAndExec(JNIEnv *env, 613 jobject process, 614 jint mode, 615 jbyteArray prog, 616 jbyteArray argBlock, jint argc, 617 jbyteArray envBlock, jint envc, 618 jbyteArray dir, 619 jintArray std_fds, 620 jboolean redirectErrorStream) 621 { 622 int errnum; 623 int resultPid = -1; 624 int in[2], out[2], err[2], fail[2], childenv[2]; 625 jint *fds = NULL; 626 const char *pprog = NULL; 627 const char *pargBlock = NULL; 628 const char *penvBlock = NULL; 629 ChildStuff *c; 630 631 in[0] = in[1] = out[0] = out[1] = err[0] = err[1] = fail[0] = fail[1] = -1; 632 childenv[0] = childenv[1] = -1; 633 634 if ((c = NEW(ChildStuff, 1)) == NULL) return -1; 635 c->argv = NULL; 636 c->envv = NULL; 637 c->pdir = NULL; 638 c->clone_stack = NULL; 639 640 /* Convert prog + argBlock into a char ** argv. 641 * Add one word room for expansion of argv for use by 642 * execve_as_traditional_shell_script. 643 * This word also used when using spawn mode 644 */ 645 assert(prog != NULL && argBlock != NULL); 646 if ((pprog = getBytes(env, prog)) == NULL) goto Catch; 647 if ((pargBlock = getBytes(env, argBlock)) == NULL) goto Catch; 648 if ((c->argv = NEW(const char *, argc + 3)) == NULL) goto Catch; 649 c->argv[0] = pprog; 650 c->argc = argc + 2; 651 initVectorFromBlock(c->argv+1, pargBlock, argc); 652 653 if (envBlock != NULL) { 654 /* Convert envBlock into a char ** envv */ 655 if ((penvBlock = getBytes(env, envBlock)) == NULL) goto Catch; 656 if ((c->envv = NEW(const char *, envc + 1)) == NULL) goto Catch; 657 initVectorFromBlock(c->envv, penvBlock, envc); 658 } 659 660 if (dir != NULL) { 661 if ((c->pdir = getBytes(env, dir)) == NULL) goto Catch; 662 } 663 664 assert(std_fds != NULL); 665 fds = (*env)->GetIntArrayElements(env, std_fds, NULL); 666 if (fds == NULL) goto Catch; 667 668 if ((fds[0] == -1 && pipe(in) < 0) || 669 (fds[1] == -1 && pipe(out) < 0) || 670 (fds[2] == -1 && pipe(err) < 0) || 671 (pipe(childenv) < 0) || 672 (pipe(fail) < 0)) { 673 throwIOException(env, errno, "Bad file descriptor"); 674 goto Catch; 675 } 676 c->fds[0] = fds[0]; 677 c->fds[1] = fds[1]; 678 c->fds[2] = fds[2]; 679 680 copyPipe(in, c->in); 681 copyPipe(out, c->out); 682 copyPipe(err, c->err); 683 copyPipe(fail, c->fail); 684 copyPipe(childenv, c->childenv); 685 686 c->redirectErrorStream = redirectErrorStream; 687 c->mode = mode; 688 689 resultPid = startChild(env, process, c); 690 assert(resultPid != 0); 691 692 if (resultPid < 0) { 693 switch (c->mode) { 694 case MODE_VFORK: 695 throwIOException(env, errno, "vfork failed"); 696 case MODE_FORK: 697 throwIOException(env, errno, "fork failed"); 698 case MODE_SPAWN: 699 throwIOException(env, errno, "spawn failed"); 700 } 701 goto Catch; 702 } 703 restartableClose(fail[1]); fail[1] = -1; /* See: WhyCantJohnnyExec */ 704 705 switch (readFully(fail[0], &errnum, sizeof(errnum))) { 706 case 0: break; /* Exec succeeded */ 707 case sizeof(errnum): 708 waitpid(resultPid, NULL, 0); 709 throwIOException(env, errnum, "Exec failed"); 710 goto Catch; 711 default: 712 throwIOException(env, errno, "Read failed"); 713 goto Catch; 714 } 715 716 fds[0] = (in [1] != -1) ? in [1] : -1; 717 fds[1] = (out[0] != -1) ? out[0] : -1; 718 fds[2] = (err[0] != -1) ? err[0] : -1; 719 720 Finally: 721 free(c->clone_stack); 722 723 /* Always clean up the child's side of the pipes */ 724 closeSafely(in [0]); 725 closeSafely(out[1]); 726 closeSafely(err[1]); 727 728 /* Always clean up fail and childEnv descriptors */ 729 closeSafely(fail[0]); 730 closeSafely(fail[1]); 731 closeSafely(childenv[0]); 732 closeSafely(childenv[1]); 733 734 releaseBytes(env, prog, pprog); 735 releaseBytes(env, argBlock, pargBlock); 736 releaseBytes(env, envBlock, penvBlock); 737 releaseBytes(env, dir, c->pdir); 738 739 free(c->argv); 740 free(c->envv); 741 free(c); 742 743 if (fds != NULL) 744 (*env)->ReleaseIntArrayElements(env, std_fds, fds, 0); 745 746 return resultPid; 747 748 Catch: 749 /* Clean up the parent's side of the pipes in case of failure only */ 750 closeSafely(in [1]); in[1] = -1; 751 closeSafely(out[0]); out[0] = -1; 752 closeSafely(err[0]); err[0] = -1; 753 goto Finally; 754 } 755 756 JNIEXPORT void JNICALL 757 Java_java_lang_UNIXProcess_destroyProcess(JNIEnv *env, 758 jobject junk, 759 jint pid, 760 jboolean force) 761 { 762 int sig = (force == JNI_TRUE) ? SIGKILL : SIGTERM; 763 kill(pid, sig); 764 }