0001
0002
0003
0004
0005
0006 #include <errno.h>
0007 #include <signal.h>
0008 #include <stdbool.h>
0009 #include <stdio.h>
0010 #include <stdlib.h>
0011 #include <sys/types.h>
0012 #include <sys/wait.h>
0013 #include <unistd.h>
0014 #include <elf.h>
0015 #include <fcntl.h>
0016 #include <link.h>
0017 #include <sys/stat.h>
0018
0019 #include "subunit.h"
0020 #include "utils.h"
0021
0022 #define KILL_TIMEOUT 5
0023
0024
0025 static uint64_t timeout = 120;
0026
0027 int run_test(int (test_function)(void), char *name)
0028 {
0029 bool terminated;
0030 int rc, status;
0031 pid_t pid;
0032
0033
0034 fflush(stdout);
0035
0036 pid = fork();
0037 if (pid == 0) {
0038 setpgid(0, 0);
0039 exit(test_function());
0040 } else if (pid == -1) {
0041 perror("fork");
0042 return 1;
0043 }
0044
0045 setpgid(pid, pid);
0046
0047 if (timeout != -1)
0048
0049 alarm(timeout);
0050 terminated = false;
0051
0052 wait:
0053 rc = waitpid(pid, &status, 0);
0054 if (rc == -1) {
0055 if (errno != EINTR) {
0056 printf("unknown error from waitpid\n");
0057 return 1;
0058 }
0059
0060 if (terminated) {
0061 printf("!! force killing %s\n", name);
0062 kill(-pid, SIGKILL);
0063 return 1;
0064 } else {
0065 printf("!! killing %s\n", name);
0066 kill(-pid, SIGTERM);
0067 terminated = true;
0068 alarm(KILL_TIMEOUT);
0069 goto wait;
0070 }
0071 }
0072
0073
0074 kill(-pid, SIGTERM);
0075
0076 if (WIFEXITED(status))
0077 status = WEXITSTATUS(status);
0078 else {
0079 if (WIFSIGNALED(status))
0080 printf("!! child died by signal %d\n", WTERMSIG(status));
0081 else
0082 printf("!! child died by unknown cause\n");
0083
0084 status = 1;
0085 }
0086
0087 return status;
0088 }
0089
0090 static void sig_handler(int signum)
0091 {
0092
0093 }
0094
0095 static struct sigaction sig_action = {
0096 .sa_handler = sig_handler,
0097 };
0098
0099 void test_harness_set_timeout(uint64_t time)
0100 {
0101 timeout = time;
0102 }
0103
0104 int test_harness(int (test_function)(void), char *name)
0105 {
0106 int rc;
0107
0108 test_start(name);
0109 test_set_git_version(GIT_VERSION);
0110
0111 if (sigaction(SIGINT, &sig_action, NULL)) {
0112 perror("sigaction (sigint)");
0113 test_error(name);
0114 return 1;
0115 }
0116
0117 if (sigaction(SIGALRM, &sig_action, NULL)) {
0118 perror("sigaction (sigalrm)");
0119 test_error(name);
0120 return 1;
0121 }
0122
0123 rc = run_test(test_function, name);
0124
0125 if (rc == MAGIC_SKIP_RETURN_VALUE) {
0126 test_skip(name);
0127
0128 rc = 0;
0129 } else
0130 test_finish(name, rc);
0131
0132 return rc;
0133 }