1 /* 2 * Copyright (c) 1995, 2015, 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) || defined(_AIX) 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 * "jprochelper", 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 posix_spawn() on other Unix systems. 101 */ 102 103 104 static void 105 setSIGCHLDHandler(JNIEnv *env) 106 { 107 /* There is a subtle difference between having the signal handler 108 * for SIGCHLD be SIG_DFL and SIG_IGN. We cannot obtain process 109 * termination information for child processes if the signal 110 * handler is SIG_IGN. It must be SIG_DFL. 111 * 112 * We used to set the SIGCHLD handler only on Linux, but it's 113 * safest to set it unconditionally. 114 * 115 * Consider what happens if java's parent process sets the SIGCHLD 116 * handler to SIG_IGN. Normally signal handlers are inherited by 117 * children, but SIGCHLD is a controversial case. Solaris appears 118 * to always reset it to SIG_DFL, but this behavior may be 119 * non-standard-compliant, and we shouldn't rely on it. 120 * 121 * References: 122 * http://www.opengroup.org/onlinepubs/7908799/xsh/exec.html 123 * http://www.pasc.org/interps/unofficial/db/p1003.1/pasc-1003.1-132.html 124 */ 125 struct sigaction sa; 126 sa.sa_handler = SIG_DFL; 127 sigemptyset(&sa.sa_mask); 128 sa.sa_flags = SA_NOCLDSTOP | SA_RESTART; 129 if (sigaction(SIGCHLD, &sa, NULL) < 0) 130 JNU_ThrowInternalError(env, "Can't set SIGCHLD handler"); 131 } 132 133 static void* 134 xmalloc(JNIEnv *env, size_t size) 135 { 136 void *p = malloc(size); 137 if (p == NULL) 138 JNU_ThrowOutOfMemoryError(env, NULL); 139 return p; 140 } 141 142 #define NEW(type, n) ((type *) xmalloc(env, (n) * sizeof(type))) 143 144 /** 145 * If PATH is not defined, the OS provides some default value. 146 * Unfortunately, there's no portable way to get this value. 147 * Fortunately, it's only needed if the child has PATH while we do not. 148 */ 149 static const char* 150 defaultPath(void) 151 { 152 #ifdef __solaris__ 153 /* These really are the Solaris defaults! */ 154 return (geteuid() == 0 || getuid() == 0) ? 155 "/usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin:/usr/sbin" : 156 "/usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin:"; 157 #else 158 return ":/bin:/usr/bin"; /* glibc */ 159 #endif 160 } 161 162 static const char* 163 effectivePath(void) 164 { 165 const char *s = getenv("PATH"); 166 return (s != NULL) ? s : defaultPath(); 167 } 168 169 static int 170 countOccurrences(const char *s, char c) 171 { 172 int count; 173 for (count = 0; *s != '\0'; s++) 174 count += (*s == c); 175 return count; 176 } 177 178 static const char * const * 179 effectivePathv(JNIEnv *env) 180 { 181 char *p; 182 int i; 183 const char *path = effectivePath(); 184 int count = countOccurrences(path, ':') + 1; 185 size_t pathvsize = sizeof(const char *) * (count+1); 186 size_t pathsize = strlen(path) + 1; 187 const char **pathv = (const char **) xmalloc(env, pathvsize + pathsize); 188 189 if (pathv == NULL) 190 return NULL; 191 p = (char *) pathv + pathvsize; 192 memcpy(p, path, pathsize); 193 /* split PATH by replacing ':' with NULs; empty components => "." */ 194 for (i = 0; i < count; i++) { 195 char *q = p + strcspn(p, ":"); 196 pathv[i] = (p == q) ? "." : p; 197 *q = '\0'; 198 p = q + 1; 199 } 200 pathv[count] = NULL; 201 return pathv; 202 } 203 204 JNIEXPORT void JNICALL 205 Java_java_lang_ProcessImpl_init(JNIEnv *env, jclass clazz) 206 { 207 parentPathv = effectivePathv(env); 208 CHECK_NULL(parentPathv); 209 setSIGCHLDHandler(env); 210 } 211 212 213 #ifndef WIFEXITED 214 #define WIFEXITED(status) (((status)&0xFF) == 0) 215 #endif 216 217 #ifndef WEXITSTATUS 218 #define WEXITSTATUS(status) (((status)>>8)&0xFF) 219 #endif 220 221 #ifndef WIFSIGNALED 222 #define WIFSIGNALED(status) (((status)&0xFF) > 0 && ((status)&0xFF00) == 0) 223 #endif 224 225 #ifndef WTERMSIG 226 #define WTERMSIG(status) ((status)&0x7F) 227 #endif 228 229 static const char * 230 getBytes(JNIEnv *env, jbyteArray arr) 231 { 232 return arr == NULL ? NULL : 233 (const char*) (*env)->GetByteArrayElements(env, arr, NULL); 234 } 235 236 static void 237 releaseBytes(JNIEnv *env, jbyteArray arr, const char* parr) 238 { 239 if (parr != NULL) 240 (*env)->ReleaseByteArrayElements(env, arr, (jbyte*) parr, JNI_ABORT); 241 } 242 243 #define IOE_FORMAT "error=%d, %s" 244 245 static void 246 throwIOException(JNIEnv *env, int errnum, const char *defaultDetail) 247 { 248 const char *detail = defaultDetail; 249 char *errmsg; 250 size_t fmtsize; 251 jstring s; 252 253 if (errnum != 0) { 254 const char *s = strerror(errnum); 255 if (strcmp(s, "Unknown error") != 0) 256 detail = s; 257 } 258 /* ASCII Decimal representation uses 2.4 times as many bits as binary. */ 259 fmtsize = sizeof(IOE_FORMAT) + strlen(detail) + 3 * sizeof(errnum); 260 errmsg = NEW(char, fmtsize); 261 if (errmsg == NULL) 262 return; 263 264 snprintf(errmsg, fmtsize, IOE_FORMAT, errnum, detail); 265 s = JNU_NewStringPlatform(env, errmsg); 266 if (s != NULL) { 267 jobject x = JNU_NewObjectByName(env, "java/io/IOException", 268 "(Ljava/lang/String;)V", s); 269 if (x != NULL) 270 (*env)->Throw(env, x); 271 } 272 free(errmsg); 273 } 274 275 #ifdef DEBUG_PROCESS 276 /* Debugging process code is difficult; where to write debug output? */ 277 static void 278 debugPrint(char *format, ...) 279 { 280 FILE *tty = fopen("/dev/tty", "w"); 281 va_list ap; 282 va_start(ap, format); 283 vfprintf(tty, format, ap); 284 va_end(ap); 285 fclose(tty); 286 } 287 #endif /* DEBUG_PROCESS */ 288 289 static void 290 copyPipe(int from[2], int to[2]) 291 { 292 to[0] = from[0]; 293 to[1] = from[1]; 294 } 295 296 /* arg is an array of pointers to 0 terminated strings. array is terminated 297 * by a null element. 298 * 299 * *nelems and *nbytes receive the number of elements of array (incl 0) 300 * and total number of bytes (incl. 0) 301 * Note. An empty array will have one null element 302 * But if arg is null, then *nelems set to 0, and *nbytes to 0 303 */ 304 static void arraysize(const char * const *arg, int *nelems, int *nbytes) 305 { 306 int i, bytes, count; 307 const char * const *a = arg; 308 char *p; 309 int *q; 310 if (arg == 0) { 311 *nelems = 0; 312 *nbytes = 0; 313 return; 314 } 315 /* count the array elements and number of bytes */ 316 for (count=0, bytes=0; *a != 0; count++, a++) { 317 bytes += strlen(*a)+1; 318 } 319 *nbytes = bytes; 320 *nelems = count+1; 321 } 322 323 /* copy the strings from arg[] into buf, starting at given offset 324 * return new offset to next free byte 325 */ 326 static int copystrings(char *buf, int offset, const char * const *arg) { 327 char *p; 328 const char * const *a; 329 int count=0; 330 331 if (arg == 0) { 332 return offset; 333 } 334 for (p=buf+offset, a=arg; *a != 0; a++) { 335 int len = strlen(*a) +1; 336 memcpy(p, *a, len); 337 p += len; 338 count += len; 339 } 340 return offset+count; 341 } 342 343 /** 344 * We are unusually paranoid; use of vfork is 345 * especially likely to tickle gcc/glibc bugs. 346 */ 347 #ifdef __attribute_noinline__ /* See: sys/cdefs.h */ 348 __attribute_noinline__ 349 #endif 350 351 static pid_t 352 vforkChild(ChildStuff *c) { 353 volatile pid_t resultPid; 354 355 /* 356 * We separate the call to vfork into a separate function to make 357 * very sure to keep stack of child from corrupting stack of parent, 358 * as suggested by the scary gcc warning: 359 * warning: variable 'foo' might be clobbered by 'longjmp' or 'vfork' 360 */ 361 resultPid = vfork(); 362 363 if (resultPid == 0) { 364 childProcess(c); 365 } 366 assert(resultPid != 0); /* childProcess never returns */ 367 return resultPid; 368 } 369 370 static pid_t 371 forkChild(ChildStuff *c) { 372 pid_t resultPid; 373 374 /* 375 * From Solaris fork(2): In Solaris 10, a call to fork() is 376 * identical to a call to fork1(); only the calling thread is 377 * replicated in the child process. This is the POSIX-specified 378 * behavior for fork(). 379 */ 380 resultPid = fork(); 381 382 if (resultPid == 0) { 383 childProcess(c); 384 } 385 assert(resultPid != 0); /* childProcess never returns */ 386 return resultPid; 387 } 388 389 #if defined(__solaris__) || defined(_ALLBSD_SOURCE) || defined(_AIX) 390 static pid_t 391 spawnChild(JNIEnv *env, jobject process, ChildStuff *c, const char *helperpath) { 392 pid_t resultPid; 393 jboolean isCopy; 394 int i, offset, rval, bufsize, magic; 395 char *buf, buf1[16]; 396 char *hlpargs[2]; 397 SpawnInfo sp; 398 399 /* need to tell helper which fd is for receiving the childstuff 400 * and which fd to send response back on 401 */ 402 snprintf(buf1, sizeof(buf1), "%d:%d", c->childenv[0], c->fail[1]); 403 /* put the fd string as argument to the helper cmd */ 404 hlpargs[0] = buf1; 405 hlpargs[1] = 0; 406 407 /* Following items are sent down the pipe to the helper 408 * after it is spawned. 409 * All strings are null terminated. All arrays of strings 410 * have an empty string for termination. 411 * - the ChildStuff struct 412 * - the SpawnInfo struct 413 * - the argv strings array 414 * - the envv strings array 415 * - the home directory string 416 * - the parentPath string 417 * - the parentPathv array 418 */ 419 /* First calculate the sizes */ 420 arraysize(c->argv, &sp.nargv, &sp.argvBytes); 421 bufsize = sp.argvBytes; 422 arraysize(c->envv, &sp.nenvv, &sp.envvBytes); 423 bufsize += sp.envvBytes; 424 sp.dirlen = c->pdir == 0 ? 0 : strlen(c->pdir)+1; 425 bufsize += sp.dirlen; 426 arraysize(parentPathv, &sp.nparentPathv, &sp.parentPathvBytes); 427 bufsize += sp.parentPathvBytes; 428 /* We need to clear FD_CLOEXEC if set in the fds[]. 429 * Files are created FD_CLOEXEC in Java. 430 * Otherwise, they will be closed when the target gets exec'd */ 431 for (i=0; i<3; i++) { 432 if (c->fds[i] != -1) { 433 int flags = fcntl(c->fds[i], F_GETFD); 434 if (flags & FD_CLOEXEC) { 435 fcntl(c->fds[i], F_SETFD, flags & (~1)); 436 } 437 } 438 } 439 440 rval = posix_spawn(&resultPid, helperpath, 0, 0, (char * const *) hlpargs, environ); 441 442 if (rval != 0) { 443 return -1; 444 } 445 446 /* now the lengths are known, copy the data */ 447 buf = NEW(char, bufsize); 448 if (buf == 0) { 449 return -1; 450 } 451 offset = copystrings(buf, 0, &c->argv[0]); 452 offset = copystrings(buf, offset, &c->envv[0]); 453 memcpy(buf+offset, c->pdir, sp.dirlen); 454 offset += sp.dirlen; 455 offset = copystrings(buf, offset, parentPathv); 456 assert(offset == bufsize); 457 458 magic = magicNumber(); 459 460 /* write the two structs and the data buffer */ 461 write(c->childenv[1], (char *)&magic, sizeof(magic)); // magic number first 462 write(c->childenv[1], (char *)c, sizeof(*c)); 463 write(c->childenv[1], (char *)&sp, sizeof(sp)); 464 write(c->childenv[1], buf, bufsize); 465 free(buf); 466 467 /* In this mode an external main() in invoked which calls back into 468 * childProcess() in this file, rather than directly 469 * via the statement below */ 470 return resultPid; 471 } 472 #endif 473 474 /* 475 * Start a child process running function childProcess. 476 * This function only returns in the parent. 477 */ 478 static pid_t 479 startChild(JNIEnv *env, jobject process, ChildStuff *c, const char *helperpath) { 480 switch (c->mode) { 481 case MODE_VFORK: 482 return vforkChild(c); 483 case MODE_FORK: 484 return forkChild(c); 485 #if defined(__solaris__) || defined(_ALLBSD_SOURCE) || defined(_AIX) 486 case MODE_POSIX_SPAWN: 487 return spawnChild(env, process, c, helperpath); 488 #endif 489 default: 490 return -1; 491 } 492 } 493 494 JNIEXPORT jint JNICALL 495 Java_java_lang_ProcessImpl_forkAndExec(JNIEnv *env, 496 jobject process, 497 jint mode, 498 jbyteArray helperpath, 499 jbyteArray prog, 500 jbyteArray argBlock, jint argc, 501 jbyteArray envBlock, jint envc, 502 jbyteArray dir, 503 jintArray std_fds, 504 jboolean redirectErrorStream) 505 { 506 int errnum; 507 int resultPid = -1; 508 int in[2], out[2], err[2], fail[2], childenv[2]; 509 jint *fds = NULL; 510 const char *phelperpath = NULL; 511 const char *pprog = NULL; 512 const char *pargBlock = NULL; 513 const char *penvBlock = NULL; 514 ChildStuff *c; 515 516 in[0] = in[1] = out[0] = out[1] = err[0] = err[1] = fail[0] = fail[1] = -1; 517 childenv[0] = childenv[1] = -1; 518 519 if ((c = NEW(ChildStuff, 1)) == NULL) return -1; 520 c->argv = NULL; 521 c->envv = NULL; 522 c->pdir = NULL; 523 524 /* Convert prog + argBlock into a char ** argv. 525 * Add one word room for expansion of argv for use by 526 * execve_as_traditional_shell_script. 527 * This word is also used when using posix_spawn mode 528 */ 529 assert(prog != NULL && argBlock != NULL); 530 if ((phelperpath = getBytes(env, helperpath)) == NULL) goto Catch; 531 if ((pprog = getBytes(env, prog)) == NULL) goto Catch; 532 if ((pargBlock = getBytes(env, argBlock)) == NULL) goto Catch; 533 if ((c->argv = NEW(const char *, argc + 3)) == NULL) goto Catch; 534 c->argv[0] = pprog; 535 c->argc = argc + 2; 536 initVectorFromBlock(c->argv+1, pargBlock, argc); 537 538 if (envBlock != NULL) { 539 /* Convert envBlock into a char ** envv */ 540 if ((penvBlock = getBytes(env, envBlock)) == NULL) goto Catch; 541 if ((c->envv = NEW(const char *, envc + 1)) == NULL) goto Catch; 542 initVectorFromBlock(c->envv, penvBlock, envc); 543 } 544 545 if (dir != NULL) { 546 if ((c->pdir = getBytes(env, dir)) == NULL) goto Catch; 547 } 548 549 assert(std_fds != NULL); 550 fds = (*env)->GetIntArrayElements(env, std_fds, NULL); 551 if (fds == NULL) goto Catch; 552 553 if ((fds[0] == -1 && pipe(in) < 0) || 554 (fds[1] == -1 && pipe(out) < 0) || 555 (fds[2] == -1 && pipe(err) < 0) || 556 (pipe(childenv) < 0) || 557 (pipe(fail) < 0)) { 558 throwIOException(env, errno, "Bad file descriptor"); 559 goto Catch; 560 } 561 c->fds[0] = fds[0]; 562 c->fds[1] = fds[1]; 563 c->fds[2] = fds[2]; 564 565 copyPipe(in, c->in); 566 copyPipe(out, c->out); 567 copyPipe(err, c->err); 568 copyPipe(fail, c->fail); 569 copyPipe(childenv, c->childenv); 570 571 c->redirectErrorStream = redirectErrorStream; 572 c->mode = mode; 573 574 resultPid = startChild(env, process, c, phelperpath); 575 assert(resultPid != 0); 576 577 if (resultPid < 0) { 578 switch (c->mode) { 579 case MODE_VFORK: 580 throwIOException(env, errno, "vfork failed"); 581 break; 582 case MODE_FORK: 583 throwIOException(env, errno, "fork failed"); 584 break; 585 case MODE_POSIX_SPAWN: 586 throwIOException(env, errno, "posix_spawn failed"); 587 break; 588 } 589 goto Catch; 590 } 591 close(fail[1]); fail[1] = -1; /* See: WhyCantJohnnyExec (childproc.c) */ 592 593 switch (readFully(fail[0], &errnum, sizeof(errnum))) { 594 case 0: break; /* Exec succeeded */ 595 case sizeof(errnum): 596 waitpid(resultPid, NULL, 0); 597 throwIOException(env, errnum, "Exec failed"); 598 goto Catch; 599 default: 600 throwIOException(env, errno, "Read failed"); 601 goto Catch; 602 } 603 604 fds[0] = (in [1] != -1) ? in [1] : -1; 605 fds[1] = (out[0] != -1) ? out[0] : -1; 606 fds[2] = (err[0] != -1) ? err[0] : -1; 607 608 Finally: 609 /* Always clean up the child's side of the pipes */ 610 closeSafely(in [0]); 611 closeSafely(out[1]); 612 closeSafely(err[1]); 613 614 /* Always clean up fail and childEnv descriptors */ 615 closeSafely(fail[0]); 616 closeSafely(fail[1]); 617 closeSafely(childenv[0]); 618 closeSafely(childenv[1]); 619 620 releaseBytes(env, helperpath, phelperpath); 621 releaseBytes(env, prog, pprog); 622 releaseBytes(env, argBlock, pargBlock); 623 releaseBytes(env, envBlock, penvBlock); 624 releaseBytes(env, dir, c->pdir); 625 626 free(c->argv); 627 free(c->envv); 628 free(c); 629 630 if (fds != NULL) 631 (*env)->ReleaseIntArrayElements(env, std_fds, fds, 0); 632 633 return resultPid; 634 635 Catch: 636 /* Clean up the parent's side of the pipes in case of failure only */ 637 closeSafely(in [1]); in[1] = -1; 638 closeSafely(out[0]); out[0] = -1; 639 closeSafely(err[0]); err[0] = -1; 640 goto Finally; 641 } 642