1 // Tests for the process descriptor API for Linux.
3 #include <sys/resource.h>
4 #include <sys/select.h>
5 #include <sys/socket.h>
21 #include "capsicum-test.h"
24 // Linux requires __WALL in order for waitpid(specific_pid,...) to
25 // see and reap any specific pid. Define this to nothing for platforms
26 // (FreeBSD) where it doesn't exist, to reduce macroing.
30 //------------------------------------------------
31 // Utilities for the tests.
33 static pid_t pdwait4_(int pd, int *status, int options, struct rusage *ru) {
35 return pdwait4(pd, status, options, ru);
37 // Simulate pdwait4() with wait4(pdgetpid()); this won't work in capability mode.
39 int rc = pdgetpid(pd, &pid);
44 return wait4(pid, status, options, ru);
48 static void print_rusage(FILE *f, struct rusage *ru) {
49 fprintf(f, " User CPU time=%ld.%06ld\n", (long)ru->ru_utime.tv_sec, (long)ru->ru_utime.tv_usec);
50 fprintf(f, " System CPU time=%ld.%06ld\n", (long)ru->ru_stime.tv_sec, (long)ru->ru_stime.tv_usec);
51 fprintf(f, " Max RSS=%ld\n", ru->ru_maxrss);
54 static void print_stat(FILE *f, const struct stat *stat) {
56 "{ .st_dev=%ld, st_ino=%ld, st_mode=%04o, st_nlink=%ld, st_uid=%d, st_gid=%d,\n"
57 " .st_rdev=%ld, .st_size=%ld, st_blksize=%ld, .st_block=%ld,\n "
58 #ifdef HAVE_STAT_BIRTHTIME
61 ".st_atime=%ld, .st_mtime=%ld, .st_ctime=%ld}\n",
62 (long)stat->st_dev, (long)stat->st_ino, stat->st_mode,
63 (long)stat->st_nlink, stat->st_uid, stat->st_gid,
64 (long)stat->st_rdev, (long)stat->st_size, (long)stat->st_blksize,
65 (long)stat->st_blocks,
66 #ifdef HAVE_STAT_BIRTHTIME
67 (long)stat->st_birthtime,
69 (long)stat->st_atime, (long)stat->st_mtime, (long)stat->st_ctime);
72 static volatile sig_atomic_t had_signal[NSIG];
73 void clear_had_signals() {
74 memset(const_cast<sig_atomic_t *>(had_signal), 0, sizeof(had_signal));
76 static void handle_signal(int x) {
80 // Check that the given child process terminates as expected.
81 void CheckChildFinished(pid_t pid, bool signaled=false) {
82 // Wait for the child to finish.
86 rc = waitpid(pid, &status, __WALL);
88 fprintf(stderr, "Warning: waitpid error %s (%d)\n", strerror(errno), errno);
89 ADD_FAILURE() << "Failed to wait for child";
91 } else if (rc == pid) {
98 EXPECT_TRUE(WIFSIGNALED(status));
100 EXPECT_TRUE(WIFEXITED(status)) << std::hex << status;
101 EXPECT_EQ(0, WEXITSTATUS(status));
106 //------------------------------------------------
107 // Basic tests of process descriptor functionality
109 TEST(Pdfork, Simple) {
112 pid_t parent = getpid_();
113 EXPECT_OK(pipe(pipefds));
114 int pid = pdfork(&pd, 0);
117 // Child: check pid values.
119 EXPECT_NE(parent, getpid_());
120 EXPECT_EQ(parent, getppid());
122 SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
123 if (verbose) fprintf(stderr, "Child waiting for exit message\n");
124 // Terminate once the parent has completed the checks
125 AWAIT_INT_MESSAGE(pipefds[1], MSG_PARENT_REQUEST_CHILD_EXIT);
126 exit(testing::Test::HasFailure());
129 // Ensure the child has started.
130 AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
133 EXPECT_PID_ALIVE(pid);
135 EXPECT_OK(pdgetpid(pd, &pid_got));
136 EXPECT_EQ(pid, pid_got);
138 // Tell the child to exit and wait until it is a zombie.
139 SEND_INT_MESSAGE(pipefds[0], MSG_PARENT_REQUEST_CHILD_EXIT);
140 // EXPECT_PID_ZOMBIE waits for up to ~500ms, that should be enough time for
141 // the child to exit successfully.
142 EXPECT_PID_ZOMBIE(pid);
145 // Wait for the the child.
148 memset(&ru, 0, sizeof(ru));
149 int waitrc = pdwait4_(pd, &status, 0, &ru);
150 EXPECT_EQ(pid, waitrc);
152 fprintf(stderr, "For pd %d pid %d:\n", pd, pid);
153 print_rusage(stderr, &ru);
155 EXPECT_PID_GONE(pid);
157 // Can only pdwait4(pd) once (as initial call reaps zombie).
158 memset(&ru, 0, sizeof(ru));
159 EXPECT_EQ(-1, pdwait4_(pd, &status, 0, &ru));
160 EXPECT_EQ(ECHILD, errno);
162 EXPECT_OK(close(pd));
165 TEST(Pdfork, InvalidFlag) {
167 int pid = pdfork(&pd, PD_DAEMON<<5);
172 EXPECT_EQ(EINVAL, errno);
173 if (pid > 0) waitpid(pid, NULL, __WALL);
176 TEST(Pdfork, TimeCheck) {
177 time_t now = time(NULL); // seconds since epoch
179 if (verbose) fprintf(stderr, "Calling pdfork around %ld\n", (long)(long)now);
182 pid_t pid = pdfork(&pd, 0);
185 // Child: check we didn't get a valid process descriptor then exit.
186 EXPECT_EQ(-1, pdgetpid(pd, &pid));
187 EXPECT_EQ(EBADF, errno);
191 #ifdef HAVE_PROCDESC_FSTAT
192 // Parent process. Ensure that [acm]times have been set correctly.
194 memset(&stat, 0, sizeof(stat));
195 EXPECT_OK(fstat(pd, &stat));
196 if (verbose) print_stat(stderr, &stat);
198 #ifdef HAVE_STAT_BIRTHTIME
199 EXPECT_GE(now, stat.st_birthtime);
200 EXPECT_EQ(stat.st_birthtime, stat.st_atime);
202 EXPECT_LT((now - stat.st_atime), 2);
203 EXPECT_EQ(stat.st_atime, stat.st_ctime);
204 EXPECT_EQ(stat.st_ctime, stat.st_mtime);
207 // Wait for the child to finish.
209 EXPECT_OK(pdgetpid(pd, &pd_pid));
210 EXPECT_EQ(pid, pd_pid);
211 CheckChildFinished(pid);
214 TEST(Pdfork, UseDescriptor) {
216 pid_t pid = pdfork(&pd, 0);
219 // Child: immediately exit
222 CheckChildFinished(pid);
225 TEST(Pdfork, NonProcessDescriptor) {
226 int fd = open("/etc/passwd", O_RDONLY);
228 // pd*() operations should fail on a non-process descriptor.
229 EXPECT_EQ(-1, pdkill(fd, SIGUSR1));
231 EXPECT_EQ(-1, pdwait4_(fd, &status, 0, NULL));
233 EXPECT_EQ(-1, pdgetpid(fd, &pid));
237 static void *SubThreadMain(void *arg) {
238 // Notify the main thread that we have started
239 if (verbose) fprintf(stderr, " subthread started: pipe=%p\n", arg);
240 SEND_INT_MESSAGE((int)(intptr_t)arg, MSG_CHILD_STARTED);
242 if (verbose) fprintf(stderr, " subthread: \"I aten't dead\"\n");
248 static void *ThreadMain(void *) {
251 EXPECT_EQ(0, pipe(pipefds));
252 pid_t child = pdfork(&pd, 0);
255 // Child: start a subthread then loop.
256 pthread_t child_subthread;
257 // Wait for the subthread startup using another pipe.
258 int thread_pipefds[2];
259 EXPECT_EQ(0, pipe(thread_pipefds));
260 EXPECT_OK(pthread_create(&child_subthread, NULL, SubThreadMain,
261 (void *)(intptr_t)thread_pipefds[0]));
263 fprintf(stderr, " pdforked process %d: waiting for subthread.\n",
266 AWAIT_INT_MESSAGE(thread_pipefds[1], MSG_CHILD_STARTED);
267 close(thread_pipefds[0]);
268 close(thread_pipefds[1]);
269 // Child: Notify parent that all threads have started
270 if (verbose) fprintf(stderr, " pdforked process %d: subthread started\n", getpid());
271 SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
273 if (verbose) fprintf(stderr, " pdforked process %d: \"I aten't dead\"\n", getpid());
278 if (verbose) fprintf(stderr, " thread generated pd %d\n", pd);
280 AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
281 if (verbose) fprintf(stderr, "[%d] got child startup message\n", getpid_());
283 // Pass the process descriptor back to the main thread.
284 return reinterpret_cast<void *>(pd);
287 TEST(Pdfork, FromThread) {
288 // Fire off a new thread to do all of the creation work.
289 pthread_t child_thread;
290 EXPECT_OK(pthread_create(&child_thread, NULL, ThreadMain, NULL));
292 EXPECT_OK(pthread_join(child_thread, &data));
293 int pd = reinterpret_cast<intptr_t>(data);
294 if (verbose) fprintf(stderr, "retrieved pd %d from terminated thread\n", pd);
298 EXPECT_OK(pdgetpid(pd, &pid));
299 EXPECT_OK(pdkill(pd, SIGKILL));
301 EXPECT_EQ(pid, pdwait4_(pd, &status, 0, NULL));
302 EXPECT_TRUE(WIFSIGNALED(status));
305 //------------------------------------------------
306 // More complicated tests.
309 // Test fixture that pdfork()s off a child process, which terminates
310 // when it receives anything on a pipe.
311 class PipePdforkBase : public ::testing::Test {
313 PipePdforkBase(int pdfork_flags) : pd_(-1), pid_(-1) {
316 EXPECT_OK(pipe(pipes));
318 int parent = getpid_();
319 if (verbose) fprintf(stderr, "[%d] about to pdfork()\n", getpid_());
320 int rc = pdfork(&pd_, pdfork_flags);
323 // Child process: blocking-read an int from the pipe then exit with that value.
324 EXPECT_NE(parent, getpid_());
325 EXPECT_EQ(parent, getppid());
326 if (verbose) fprintf(stderr, " [%d] child of %d waiting for value on pipe\n", getpid_(), getppid());
327 read(pipes[0], &rc, sizeof(rc));
328 if (verbose) fprintf(stderr, " [%d] got value %d on pipe, exiting\n", getpid_(), rc);
332 usleep(100); // ensure the child has a chance to run
335 // Terminate by any means necessary.
337 pdkill(pd_, SIGKILL);
342 waitpid(pid_, NULL, __WALL|WNOHANG);
344 // Check signal expectations.
345 EXPECT_FALSE(had_signal[SIGCHLD]);
347 int TerminateChild() {
348 // Tell the child to exit.
350 if (verbose) fprintf(stderr, "[%d] write 0 to pipe\n", getpid_());
351 return write(pipe_, &zero, sizeof(zero));
359 class PipePdfork : public PipePdforkBase {
361 PipePdfork() : PipePdforkBase(0) {}
364 class PipePdforkDaemon : public PipePdforkBase {
366 PipePdforkDaemon() : PipePdforkBase(PD_DAEMON) {}
369 // Can we poll a process descriptor?
370 TEST_F(PipePdfork, Poll) {
371 // Poll the process descriptor, nothing happening.
374 fdp.events = POLLIN | POLLERR | POLLHUP;
376 EXPECT_EQ(0, poll(&fdp, 1, 0));
380 // Poll again, should have activity on the process descriptor.
381 EXPECT_EQ(1, poll(&fdp, 1, 2000));
382 EXPECT_TRUE(fdp.revents & POLLHUP);
384 // Poll a third time, still have POLLHUP.
386 EXPECT_EQ(1, poll(&fdp, 1, 0));
387 EXPECT_TRUE(fdp.revents & POLLHUP);
390 // Can multiple processes poll on the same descriptor?
391 TEST_F(PipePdfork, PollMultiple) {
393 EXPECT_EQ(0, pipe(pipefds));
398 // Child: wait for parent to acknowledge startup
399 SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
400 // Child: wait for two messages from the parent and the forked process
401 // before telling the other process to terminate.
402 if (verbose) fprintf(stderr, "[%d] waiting for read 1\n", getpid_());
403 AWAIT_INT_MESSAGE(pipefds[1], MSG_PARENT_REQUEST_CHILD_EXIT);
404 if (verbose) fprintf(stderr, "[%d] waiting for read 2\n", getpid_());
405 AWAIT_INT_MESSAGE(pipefds[1], MSG_PARENT_REQUEST_CHILD_EXIT);
407 if (verbose) fprintf(stderr, "[%d] about to exit\n", getpid_());
408 exit(testing::Test::HasFailure());
411 AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
412 if (verbose) fprintf(stderr, "[%d] got child startup message\n", getpid_());
417 // pid A: main process, here
418 // |--pid B: pdfork()ed process, blocked on read()
419 // |--pid C: fork()ed process, in read() above
420 // +--pid D: doppel process, here
422 // Both A and D execute the following code.
423 // First, check no activity on the process descriptor yet.
426 fdp.events = POLLIN | POLLERR | POLLHUP;
428 EXPECT_EQ(0, poll(&fdp, 1, 0));
430 // Both A and D ask C to exit, allowing it to do so.
431 if (verbose) fprintf(stderr, "[%d] telling child to exit\n", getpid_());
432 SEND_INT_MESSAGE(pipefds[0], MSG_PARENT_REQUEST_CHILD_EXIT);
435 // Now, wait (indefinitely) for activity on the process descriptor.
437 // - pid C will finish its two read() calls, write to the pipe and exit.
438 // - pid B will unblock from read(), and exit
439 // - this will generate an event on the process descriptor...
440 // - ...in both process A and process D.
441 if (verbose) fprintf(stderr, "[%d] waiting for child to exit\n", getpid_());
442 EXPECT_EQ(1, poll(&fdp, 1, 2000));
443 EXPECT_TRUE(fdp.revents & POLLHUP);
446 // Child: process D exits.
449 // Parent: wait on process D.
451 waitpid(doppel, &rc, __WALL);
452 EXPECT_TRUE(WIFEXITED(rc));
453 EXPECT_EQ(0, WEXITSTATUS(rc));
454 // Also wait on process B.
455 CheckChildFinished(child);
459 // Check that exit status/rusage for a dead pdfork()ed child can be retrieved
460 // via any process descriptor, multiple times.
461 TEST_F(PipePdfork, MultipleRetrieveExitStatus) {
462 EXPECT_PID_ALIVE(pid_);
463 int pd_copy = dup(pd_);
464 EXPECT_LT(0, TerminateChild());
468 memset(&ru, 0, sizeof(ru));
469 int waitrc = pdwait4_(pd_copy, &status, 0, &ru);
470 EXPECT_EQ(pid_, waitrc);
472 fprintf(stderr, "For pd %d -> pid %d:\n", pd_, pid_);
473 print_rusage(stderr, &ru);
475 EXPECT_PID_GONE(pid_);
478 // Child has been reaped, so original process descriptor dangles but
479 // still has access to rusage information.
480 memset(&ru, 0, sizeof(ru));
481 EXPECT_EQ(0, pdwait4_(pd_, &status, 0, &ru));
486 TEST_F(PipePdfork, ChildExit) {
487 EXPECT_PID_ALIVE(pid_);
488 EXPECT_LT(0, TerminateChild());
489 EXPECT_PID_DEAD(pid_);
492 int rc = pdwait4_(pd_, &status, 0, NULL);
498 #ifdef HAVE_PROC_FDINFO
499 TEST_F(PipePdfork, FdInfo) {
501 sprintf(buffer, "/proc/%d/fdinfo/%d", getpid_(), pd_);
502 int procfd = open(buffer, O_RDONLY);
505 EXPECT_OK(read(procfd, buffer, sizeof(buffer)));
506 // The fdinfo should include the file pos of the underlying file
507 EXPECT_NE((char*)NULL, strstr(buffer, "pos:\t0")) << buffer;
508 // ...and the underlying pid
510 sprintf(pidline, "pid:\t%d", pid_);
511 EXPECT_NE((char*)NULL, strstr(buffer, pidline)) << buffer;
516 // Closing a normal process descriptor terminates the underlying process.
517 TEST_F(PipePdfork, Close) {
518 sighandler_t original = signal(SIGCHLD, handle_signal);
519 EXPECT_PID_ALIVE(pid_);
521 EXPECT_EQ(0, waitpid(pid_, &status, __WALL|WNOHANG));
523 EXPECT_OK(close(pd_));
525 EXPECT_FALSE(had_signal[SIGCHLD]);
526 EXPECT_PID_DEAD(pid_);
529 EXPECT_EQ(-1, waitpid(pid_, NULL, __WALL));
530 EXPECT_EQ(errno, ECHILD);
532 // Having closed the process descriptor means that pdwait4(pd) now doesn't work.
533 int rc = pdwait4_(pd_, &status, 0, NULL);
535 EXPECT_EQ(EBADF, errno);
537 // Closing all process descriptors means the the child can only be reaped via pid.
538 EXPECT_EQ(pid_, waitpid(pid_, &status, __WALL|WNOHANG));
540 signal(SIGCHLD, original);
543 TEST_F(PipePdfork, CloseLast) {
544 sighandler_t original = signal(SIGCHLD, handle_signal);
545 // Child should only die when last process descriptor is closed.
546 EXPECT_PID_ALIVE(pid_);
547 int pd_other = dup(pd_);
549 EXPECT_OK(close(pd_));
552 EXPECT_PID_ALIVE(pid_);
554 EXPECT_EQ(0, waitpid(pid_, &status, __WALL|WNOHANG));
556 // Can no longer pdwait4() the closed process descriptor...
557 EXPECT_EQ(-1, pdwait4_(pd_, &status, WNOHANG, NULL));
558 EXPECT_EQ(EBADF, errno);
559 // ...but can pdwait4() the still-open process descriptor.
561 EXPECT_EQ(0, pdwait4_(pd_other, &status, WNOHANG, NULL));
564 EXPECT_OK(close(pd_other));
565 EXPECT_PID_DEAD(pid_);
567 EXPECT_FALSE(had_signal[SIGCHLD]);
568 signal(SIGCHLD, original);
571 FORK_TEST(Pdfork, OtherUserIfRoot) {
572 GTEST_SKIP_IF_NOT_ROOT();
575 pid_t pid = pdfork(&pd, 0);
578 // Child process: loop forever.
579 while (true) usleep(100000);
583 // Now that the second process has been pdfork()ed, change euid.
584 ASSERT_NE(0u, other_uid) << "other_uid not initialized correctly, "
585 "please pass the -u <uid> flag.";
586 EXPECT_EQ(0, setuid(other_uid));
587 EXPECT_EQ(other_uid, getuid());
588 if (verbose) fprintf(stderr, "uid=%d euid=%d\n", getuid(), geteuid());
590 // Fail to kill child with normal PID operation.
591 EXPECT_EQ(-1, kill(pid, SIGKILL));
592 EXPECT_EQ(EPERM, errno);
593 EXPECT_PID_ALIVE(pid);
595 // Ideally, we should be able to send signals via a process descriptor even
596 // if it's owned by another user, but this is not implementated on FreeBSD.
598 // On FreeBSD, pdkill() still performs all the same checks that kill() does
599 // and therefore cannot be used to send a signal to a process with another
600 // UID unless we are root.
601 EXPECT_SYSCALL_FAIL(EBADF, pdkill(pid, SIGKILL));
602 EXPECT_PID_ALIVE(pid);
603 // However, the process will be killed when we close the process descriptor.
604 EXPECT_OK(close(pd));
605 EXPECT_PID_GONE(pid);
606 // Can't pdwait4() after close() since close() reparents the child to a reaper (init)
607 EXPECT_SYSCALL_FAIL(EBADF, pdwait4_(pd, &status, WNOHANG, NULL));
609 // Sending a signal with pdkill() should be permitted though.
610 EXPECT_OK(pdkill(pd, SIGKILL));
611 EXPECT_PID_ZOMBIE(pid);
613 int rc = pdwait4_(pd, &status, WNOHANG, NULL);
616 EXPECT_TRUE(WIFSIGNALED(status));
620 TEST_F(PipePdfork, WaitPidThenPd) {
623 // If we waitpid(pid) first...
624 int rc = waitpid(pid_, &status, __WALL);
629 // ...the zombie is reaped but we can still subsequently pdwait4(pd).
630 EXPECT_EQ(0, pdwait4_(pd_, &status, 0, NULL));
634 TEST_F(PipePdfork, WaitPdThenPid) {
637 // If we pdwait4(pd) first...
638 int rc = pdwait4_(pd_, &status, 0, NULL);
642 // ...the zombie is reaped and cannot subsequently waitpid(pid).
643 EXPECT_EQ(-1, waitpid(pid_, &status, __WALL));
644 EXPECT_EQ(ECHILD, errno);
647 // Setting PD_DAEMON prevents close() from killing the child.
648 TEST_F(PipePdforkDaemon, Close) {
649 EXPECT_OK(close(pd_));
651 EXPECT_PID_ALIVE(pid_);
653 // Can still explicitly kill it via the pid.
655 EXPECT_OK(kill(pid_, SIGKILL));
656 EXPECT_PID_DEAD(pid_);
660 static void TestPdkill(pid_t pid, int pd) {
661 EXPECT_PID_ALIVE(pid);
662 // SIGCONT is ignored by default.
663 EXPECT_OK(pdkill(pd, SIGCONT));
664 EXPECT_PID_ALIVE(pid);
667 EXPECT_OK(pdkill(pd, SIGINT));
668 EXPECT_PID_DEAD(pid);
670 // pdkill() on zombie is no-op.
672 EXPECT_EQ(0, pdkill(pd, SIGINT));
675 // pdkill() on reaped process gives -ESRCH.
676 CheckChildFinished(pid, true);
677 EXPECT_EQ(-1, pdkill(pd, SIGINT));
678 EXPECT_EQ(ESRCH, errno);
681 TEST_F(PipePdfork, Pdkill) {
682 TestPdkill(pid_, pd_);
685 TEST_F(PipePdforkDaemon, Pdkill) {
686 TestPdkill(pid_, pd_);
689 TEST(Pdfork, PdkillOtherSignal) {
692 EXPECT_EQ(0, pipe(pipefds));
693 int pid = pdfork(&pd, 0);
696 // Child: tell the parent that we have started before entering the loop,
697 // and importantly only do so once we have registered the SIGUSR1 handler.
700 signal(SIGUSR1, handle_signal);
701 SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
702 // Child: watch for SIGUSR1 forever.
703 while (!had_signal[SIGUSR1]) {
708 // Wait for child to start
710 AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
713 // Send an invalid signal.
714 EXPECT_EQ(-1, pdkill(pd, 0xFFFF));
715 EXPECT_EQ(EINVAL, errno);
717 // Send an expected SIGUSR1 to the pdfork()ed child.
718 EXPECT_PID_ALIVE(pid);
720 EXPECT_PID_DEAD(pid);
722 // Child's exit status confirms whether it received the signal.
724 int rc = waitpid(pid, &status, __WALL);
727 EXPECT_TRUE(WIFEXITED(status)) << "status: 0x" << std::hex << status;
728 EXPECT_EQ(123, WEXITSTATUS(status));
731 pid_t PdforkParentDeath(int pdfork_flags) {
733 // pid A: main process, here
734 // +--pid B: fork()ed process, starts a child process with pdfork() then
735 // waits for parent to send a shutdown message.
736 // +--pid C: pdfork()ed process, looping forever
738 EXPECT_OK(socketpair(AF_UNIX, SOCK_STREAM, 0, sock_fds));
739 if (verbose) fprintf(stderr, "[%d] parent about to fork()...\n", getpid_());
740 pid_t child = fork();
744 if (verbose) fprintf(stderr, " [%d] child about to pdfork()...\n", getpid_());
745 int pipefds[2]; // for startup notification
746 EXPECT_OK(pipe(pipefds));
747 pid_t grandchild = pdfork(&pd, pdfork_flags);
748 if (grandchild == 0) {
750 pid_t grandchildPid = getpid_();
751 EXPECT_EQ(sizeof(grandchildPid), (size_t)write(pipefds[1], &grandchildPid, sizeof(grandchildPid)));
753 if (verbose) fprintf(stderr, " [%d] grandchild: \"I aten't dead\"\n", grandchildPid);
758 if (verbose) fprintf(stderr, " [%d] pdfork()ed grandchild %d, sending ID to parent\n", getpid_(), grandchild);
759 // Wait for grandchild to start.
761 EXPECT_EQ(sizeof(grandchild2), (size_t)read(pipefds[0], &grandchild2, sizeof(grandchild2)));
762 EXPECT_EQ(grandchild, grandchild2) << "received invalid grandchild pid";
763 if (verbose) fprintf(stderr, " [%d] grandchild %d has started successfully\n", getpid_(), grandchild);
766 // Send grandchild pid to parent.
767 EXPECT_EQ(sizeof(grandchild), (size_t)write(sock_fds[1], &grandchild, sizeof(grandchild)));
768 if (verbose) fprintf(stderr, " [%d] sent grandchild pid %d to parent\n", getpid_(), grandchild);
769 // Wait for parent to acknowledge the message.
770 AWAIT_INT_MESSAGE(sock_fds[1], MSG_PARENT_REQUEST_CHILD_EXIT);
771 if (verbose) fprintf(stderr, " [%d] parent acknowledged grandchild pid %d\n", getpid_(), grandchild);
772 if (verbose) fprintf(stderr, " [%d] child terminating\n", getpid_());
773 exit(testing::Test::HasFailure());
775 if (verbose) fprintf(stderr, "[%d] fork()ed child is %d\n", getpid_(), child);
777 read(sock_fds[0], &grandchild, sizeof(grandchild));
778 if (verbose) fprintf(stderr, "[%d] received grandchild id %d\n", getpid_(), grandchild);
779 EXPECT_PID_ALIVE(child);
780 EXPECT_PID_ALIVE(grandchild);
781 // Tell child to exit.
782 if (verbose) fprintf(stderr, "[%d] telling child %d to exit\n", getpid_(), child);
783 SEND_INT_MESSAGE(sock_fds[0], MSG_PARENT_REQUEST_CHILD_EXIT);
784 // Child dies, closing its process descriptor for the grandchild.
785 EXPECT_PID_DEAD(child);
786 CheckChildFinished(child);
790 TEST(Pdfork, Bagpuss) {
791 // "And of course when Bagpuss goes to sleep, all his friends go to sleep too"
792 pid_t grandchild = PdforkParentDeath(0);
793 // By default: child death => closed process descriptor => grandchild death.
794 EXPECT_PID_DEAD(grandchild);
797 TEST(Pdfork, BagpussDaemon) {
798 pid_t grandchild = PdforkParentDeath(PD_DAEMON);
799 // With PD_DAEMON: child death => closed process descriptor => no effect on grandchild.
800 EXPECT_PID_ALIVE(grandchild);
801 if (grandchild > 0) {
802 EXPECT_OK(kill(grandchild, SIGKILL));
806 // The exit of a pdfork()ed process should not generate SIGCHLD.
807 TEST_F(PipePdfork, NoSigchld) {
809 sighandler_t original = signal(SIGCHLD, handle_signal);
812 // Can waitpid() for the specific pid of the pdfork()ed child.
813 EXPECT_EQ(pid_, waitpid(pid_, &rc, __WALL));
814 EXPECT_TRUE(WIFEXITED(rc)) << "0x" << std::hex << rc;
815 EXPECT_FALSE(had_signal[SIGCHLD]);
816 signal(SIGCHLD, original);
819 // The exit of a pdfork()ed process whose process descriptors have
820 // all been closed should generate SIGCHLD. The child process needs
821 // PD_DAEMON to survive the closure of the process descriptors.
822 TEST_F(PipePdforkDaemon, NoPDSigchld) {
824 sighandler_t original = signal(SIGCHLD, handle_signal);
826 EXPECT_OK(close(pd_));
829 EXPECT_EQ(-1, waitpid(pid_, NULL, __WALL));
830 EXPECT_EQ(errno, ECHILD);
833 // Can waitpid() for the specific pid of the pdfork()ed child.
834 EXPECT_EQ(pid_, waitpid(pid_, &rc, __WALL));
835 EXPECT_TRUE(WIFEXITED(rc)) << "0x" << std::hex << rc;
837 EXPECT_FALSE(had_signal[SIGCHLD]);
838 signal(SIGCHLD, original);
841 #ifdef HAVE_PROCDESC_FSTAT
842 TEST_F(PipePdfork, ModeBits) {
843 // Owner rwx bits indicate liveness of child
845 memset(&stat, 0, sizeof(stat));
846 EXPECT_OK(fstat(pd_, &stat));
847 if (verbose) print_stat(stderr, &stat);
848 EXPECT_EQ(S_IRWXU, (long)(stat.st_mode & S_IRWXU));
853 memset(&stat, 0, sizeof(stat));
854 EXPECT_OK(fstat(pd_, &stat));
855 if (verbose) print_stat(stderr, &stat);
856 EXPECT_EQ(0, (int)(stat.st_mode & S_IRWXU));
860 TEST_F(PipePdfork, WildcardWait) {
862 EXPECT_PID_ZOMBIE(pid_); // Ensure child is truly dead.
864 // Wildcard waitpid(-1) should not see the pdfork()ed child because
865 // there is still a process descriptor for it.
867 EXPECT_EQ(-1, waitpid(-1, &rc, WNOHANG));
868 EXPECT_EQ(ECHILD, errno);
870 EXPECT_OK(close(pd_));
874 FORK_TEST(Pdfork, Pdkill) {
878 EXPECT_OK(pipe(pipefds));
879 pid_t pid = pdfork(&pd, 0);
883 // Child: set a SIGINT handler, notify the parent and sleep.
886 signal(SIGINT, handle_signal);
887 if (verbose) fprintf(stderr, "[%d] child started\n", getpid_());
888 SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
889 if (verbose) fprintf(stderr, "[%d] child about to sleep(10)\n", getpid_());
890 // Note: we could receive the SIGINT just before sleep(), so we use a loop
891 // with a short delay instead of one long sleep().
892 for (int i = 0; i < 50 && !had_signal[SIGINT]; i++) {
895 if (verbose) fprintf(stderr, "[%d] child slept, had[SIGINT]=%d\n",
896 getpid_(), (int)had_signal[SIGINT]);
897 // Return non-zero if we didn't see SIGINT.
898 exit(had_signal[SIGINT] ? 0 : 99);
901 // Parent: get child's PID.
903 EXPECT_OK(pdgetpid(pd, &pd_pid));
904 EXPECT_EQ(pid, pd_pid);
906 // Interrupt the child once it's registered the SIGINT handler.
908 if (verbose) fprintf(stderr, "[%d] waiting for child\n", getpid_());
909 AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
910 EXPECT_OK(pdkill(pd, SIGINT));
911 if (verbose) fprintf(stderr, "[%d] sent SIGINT\n", getpid_());
913 // Make sure the child finished properly (caught signal then exited).
914 CheckChildFinished(pid);
917 FORK_TEST(Pdfork, PdkillSignal) {
920 EXPECT_OK(pipe(pipefds));
921 pid_t pid = pdfork(&pd, 0);
926 if (verbose) fprintf(stderr, "[%d] child started\n", getpid_());
927 SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
928 // Child: wait for shutdown message. No SIGINT handler. The message should
929 // never be received, since SIGINT should terminate the process.
930 if (verbose) fprintf(stderr, "[%d] child about to read()\n", getpid_());
931 AWAIT_INT_MESSAGE(pipefds[1], MSG_PARENT_REQUEST_CHILD_EXIT);
932 fprintf(stderr, "[%d] child read() returned unexpectedly\n", getpid_());
935 // Wait for child to start before signalling.
936 if (verbose) fprintf(stderr, "[%d] waiting for child\n", getpid_());
938 AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
939 // Kill the child (as it doesn't handle SIGINT).
940 if (verbose) fprintf(stderr, "[%d] sending SIGINT\n", getpid_());
941 EXPECT_OK(pdkill(pd, SIGINT));
943 // Make sure the child finished properly (terminated by signal).
944 CheckChildFinished(pid, true);
947 //------------------------------------------------
948 // Test interactions with other parts of Capsicum:
952 FORK_TEST(Pdfork, DaemonUnrestricted) {
953 EXPECT_OK(cap_enter());
956 // Capability mode leaves pdfork() available, with and without flag.
958 rc = pdfork(&fd, PD_DAEMON);
961 // Child: immediately terminate.
968 // Child: immediately terminate.
973 TEST(Pdfork, MissingRights) {
974 pid_t parent = getpid_();
976 pid_t pid = pdfork(&pd, 0);
979 // Child: loop forever.
980 EXPECT_NE(parent, getpid_());
981 while (true) sleep(1);
983 // Create two capabilities from the process descriptor.
985 cap_rights_init(&r_ro, CAP_READ, CAP_LOOKUP);
986 int cap_incapable = dup(pd);
987 EXPECT_OK(cap_incapable);
988 EXPECT_OK(cap_rights_limit(cap_incapable, &r_ro));
989 cap_rights_t r_pdall;
990 cap_rights_init(&r_pdall, CAP_PDGETPID, CAP_PDWAIT, CAP_PDKILL);
991 int cap_capable = dup(pd);
992 EXPECT_OK(cap_capable);
993 EXPECT_OK(cap_rights_limit(cap_capable, &r_pdall));
996 EXPECT_NOTCAPABLE(pdgetpid(cap_incapable, &other_pid));
997 EXPECT_NOTCAPABLE(pdkill(cap_incapable, SIGINT));
999 EXPECT_NOTCAPABLE(pdwait4_(cap_incapable, &status, 0, NULL));
1001 EXPECT_OK(pdgetpid(cap_capable, &other_pid));
1002 EXPECT_EQ(pid, other_pid);
1003 EXPECT_OK(pdkill(cap_capable, SIGINT));
1004 int rc = pdwait4_(pd, &status, 0, NULL);
1010 //------------------------------------------------
1011 // Passing process descriptors between processes.
1013 TEST_F(PipePdfork, PassProcessDescriptor) {
1015 EXPECT_OK(socketpair(AF_UNIX, SOCK_STREAM, 0, sock_fds));
1018 mh.msg_name = NULL; // No address needed
1021 struct iovec iov[1];
1022 iov[0].iov_base = buffer1;
1023 iov[0].iov_len = sizeof(buffer1);
1027 mh.msg_control = buffer2;
1028 mh.msg_controllen = sizeof(buffer2);
1029 struct cmsghdr *cmptr;
1031 if (verbose) fprintf(stderr, "[%d] about to fork()\n", getpid_());
1032 pid_t child2 = fork();
1034 // Child: close our copy of the original process descriptor.
1036 SEND_INT_MESSAGE(sock_fds[0], MSG_CHILD_STARTED);
1037 // Child: wait to receive process descriptor over socket
1038 if (verbose) fprintf(stderr, " [%d] child of %d waiting for process descriptor on socket\n", getpid_(), getppid());
1039 int rc = recvmsg(sock_fds[0], &mh, 0);
1041 EXPECT_LE(CMSG_LEN(sizeof(int)), mh.msg_controllen);
1042 cmptr = CMSG_FIRSTHDR(&mh);
1043 int pd = *(int*)CMSG_DATA(cmptr);
1044 EXPECT_EQ(CMSG_LEN(sizeof(int)), cmptr->cmsg_len);
1045 cmptr = CMSG_NXTHDR(&mh, cmptr);
1046 EXPECT_TRUE(cmptr == NULL);
1047 if (verbose) fprintf(stderr, " [%d] got process descriptor %d on socket\n", getpid_(), pd);
1048 SEND_INT_MESSAGE(sock_fds[0], MSG_CHILD_FD_RECEIVED);
1050 // Child: confirm we can do pd*() operations on the process descriptor
1052 EXPECT_OK(pdgetpid(pd, &other));
1053 if (verbose) fprintf(stderr, " [%d] process descriptor %d is pid %d\n", getpid_(), pd, other);
1055 // Wait until the parent has closed the process descriptor.
1056 AWAIT_INT_MESSAGE(sock_fds[0], MSG_PARENT_CLOSED_FD);
1058 if (verbose) fprintf(stderr, " [%d] close process descriptor %d\n", getpid_(), pd);
1061 // Last process descriptor closed, expect death
1062 EXPECT_PID_DEAD(other);
1066 // Wait until the child has started.
1067 AWAIT_INT_MESSAGE(sock_fds[1], MSG_CHILD_STARTED);
1069 // Send the process descriptor over the pipe to the sub-process
1070 mh.msg_controllen = CMSG_LEN(sizeof(int));
1071 cmptr = CMSG_FIRSTHDR(&mh);
1072 cmptr->cmsg_level = SOL_SOCKET;
1073 cmptr->cmsg_type = SCM_RIGHTS;
1074 cmptr->cmsg_len = CMSG_LEN(sizeof(int));
1075 *(int *)CMSG_DATA(cmptr) = pd_;
1078 if (verbose) fprintf(stderr, "[%d] send process descriptor %d on socket\n", getpid_(), pd_);
1079 int rc = sendmsg(sock_fds[1], &mh, 0);
1081 // Wait until the child has received the process descriptor.
1082 AWAIT_INT_MESSAGE(sock_fds[1], MSG_CHILD_FD_RECEIVED);
1084 if (verbose) fprintf(stderr, "[%d] close process descriptor %d\n", getpid_(), pd_);
1085 close(pd_); // Not last open process descriptor
1086 SEND_INT_MESSAGE(sock_fds[1], MSG_PARENT_CLOSED_FD);
1090 EXPECT_EQ(child2, waitpid(child2, &status, __WALL));
1091 rc = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
1094 // confirm death all round
1095 EXPECT_PID_DEAD(child2);
1096 EXPECT_PID_DEAD(pid_);