11 #include <sys/types.h>
17 #include <ccan/read_write_all/read_write_all.h>
18 #include <ccan/failtest/failtest_proto.h>
19 #include <ccan/failtest/failtest.h>
20 #include <ccan/build_assert/build_assert.h>
22 enum failtest_result (*failtest_hook)(struct failtest_call *, unsigned);
24 static int tracefd = -1;
26 unsigned int failtest_timeout_ms = 20000;
29 const char *debugpath;
41 /* end is inclusive: you can't have a 0-byte lock. */
46 bool (*failtest_exit_check)(struct failtest_call *history, unsigned num);
48 static struct failtest_call *history = NULL;
49 static unsigned int history_num = 0;
50 static int control_fd = -1;
51 static struct timeval start;
52 static unsigned int probe_count = 0;
54 static struct write_call *child_writes = NULL;
55 static unsigned int child_writes_num = 0;
57 static pid_t lock_owner;
58 static struct lock_info *locks = NULL;
59 static unsigned int lock_num = 0;
61 static pid_t orig_pid;
63 static const char info_to_arg[] = "mceoxprwf";
65 /* Dummy call used for failtest_undo wrappers. */
66 static struct failtest_call unrecorded_call;
68 static struct failtest_call *add_history_(enum failtest_call_type type,
74 /* NULL file is how we suppress failure. */
76 return &unrecorded_call;
78 history = realloc(history, (history_num + 1) * sizeof(*history));
79 history[history_num].type = type;
80 history[history_num].file = file;
81 history[history_num].line = line;
82 history[history_num].cleanup = NULL;
83 memcpy(&history[history_num].u, elem, elem_size);
84 return &history[history_num++];
87 #define add_history(type, file, line, elem) \
88 add_history_((type), (file), (line), (elem), sizeof(*(elem)))
90 /* We do a fake call inside a sizeof(), to check types. */
91 #define set_cleanup(call, clean, type) \
92 (call)->cleanup = (void *)((void)sizeof(clean((type *)NULL),1), (clean))
94 static bool read_write_info(int fd)
99 /* We don't need all of this, but it's simple. */
100 child_writes = realloc(child_writes,
101 (child_writes_num+1) * sizeof(child_writes[0]));
102 w = &child_writes[child_writes_num];
103 if (!read_all(fd, w, sizeof(*w)))
106 w->buf = buf = malloc(w->count);
107 if (!read_all(fd, buf, w->count))
114 static char *failpath_string(void)
117 char *ret = malloc(history_num + 1);
119 for (i = 0; i < history_num; i++) {
120 ret[i] = info_to_arg[history[i].type];
122 ret[i] = toupper(ret[i]);
128 static void tell_parent(enum info_type type)
130 if (control_fd != -1)
131 write_all(control_fd, &type, sizeof(type));
134 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
137 char *path = failpath_string();
140 vfprintf(stderr, fmt, ap);
143 fprintf(stderr, "%.*s", (int)outlen, out);
144 printf("To reproduce: --failpath=%s\n", path);
146 tell_parent(FAILURE);
150 static void trace(const char *fmt, ...)
158 vdprintf(tracefd, fmt, ap);
164 static void hand_down(int signum)
169 static void release_locks(void)
171 /* Locks were never acquired/reacquired? */
175 /* We own them? Release them all. */
176 if (lock_owner == getpid()) {
180 fl.l_whence = SEEK_SET;
184 for (i = 0; i < lock_num; i++)
185 fcntl(locks[i].fd, F_SETLK, &fl);
187 /* Our parent must have them; pass request up. */
188 enum info_type type = RELEASE_LOCKS;
189 assert(control_fd != -1);
190 write_all(control_fd, &type, sizeof(type));
195 /* off_t is a signed type. Getting its max is non-trivial. */
196 static off_t off_max(void)
198 BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
199 if (sizeof(off_t) == 4)
200 return (off_t)0x7FFFFFF;
202 return (off_t)0x7FFFFFFFFFFFFFFULL;
205 static void get_locks(void)
210 if (lock_owner == getpid())
213 if (lock_owner != 0) {
214 enum info_type type = RELEASE_LOCKS;
215 assert(control_fd != -1);
216 write_all(control_fd, &type, sizeof(type));
219 fl.l_whence = SEEK_SET;
221 for (i = 0; i < lock_num; i++) {
222 fl.l_type = locks[i].type;
223 fl.l_start = locks[i].start;
224 if (locks[i].end == off_max())
227 fl.l_len = locks[i].end - locks[i].start + 1;
229 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
232 lock_owner = getpid();
236 struct saved_file *next;
242 static struct saved_file *save_file(struct saved_file *next, int fd)
244 struct saved_file *s = malloc(sizeof(*s));
248 s->off = lseek(fd, 0, SEEK_CUR);
249 /* Special file? Erk... */
250 assert(s->off != -1);
251 s->len = lseek(fd, 0, SEEK_END);
252 lseek(fd, 0, SEEK_SET);
253 s->contents = malloc(s->len);
254 if (read(fd, s->contents, s->len) != s->len)
255 err(1, "Failed to save %zu bytes", (size_t)s->len);
256 lseek(fd, s->off, SEEK_SET);
260 /* We have little choice but to save and restore open files: mmap means we
261 * can really intercept changes in the child.
263 * We could do non-mmap'ed files on demand, however. */
264 static struct saved_file *save_files(void)
266 struct saved_file *files = NULL;
269 /* Figure out the set of live fds. */
270 for (i = history_num - 2; i >= 0; i--) {
271 if (history[i].type == FAILTEST_OPEN) {
272 int fd = history[i].u.open.ret;
273 /* Only do successful, writable fds. */
277 /* If it was closed, cleanup == NULL. */
278 if (!history[i].cleanup)
281 if ((history[i].u.open.flags & O_RDWR) == O_RDWR) {
282 files = save_file(files, fd);
283 } else if ((history[i].u.open.flags & O_WRONLY)
285 /* FIXME: Handle O_WRONLY. Open with O_RDWR? */
294 static void restore_files(struct saved_file *s)
297 struct saved_file *next = s->next;
299 lseek(s->fd, 0, SEEK_SET);
300 if (write(s->fd, s->contents, s->len) != s->len)
301 err(1, "Failed to restore %zu bytes", (size_t)s->len);
302 if (ftruncate(s->fd, s->len) != 0)
303 err(1, "Failed to trim file to length %zu",
306 lseek(s->fd, s->off, SEEK_SET);
312 /* Free up memory, so valgrind doesn't report leaks. */
313 static void free_everything(void)
317 /* We don't do this in cleanup: needed even for failed opens. */
318 for (i = 0; i < history_num; i++) {
319 if (history[i].type == FAILTEST_OPEN)
320 free((char *)history[i].u.open.pathname);
325 static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
329 /* For children, we don't care if they "failed" the testing. */
330 if (control_fd != -1)
336 /* Cleanup everything, in reverse order. */
337 for (i = history_num - 1; i >= 0; i--) {
338 if (!history[i].cleanup)
340 if (!forced_cleanup) {
341 printf("Leak at %s:%u: --failpath=%s\n",
342 history[i].file, history[i].line,
346 history[i].cleanup(&history[i].u);
350 tell_parent(SUCCESS);
354 static bool should_fail(struct failtest_call *call)
357 int control[2], output[2];
358 enum info_type type = UNEXPECTED;
361 struct saved_file *files;
363 /* Are we probing? */
364 if (probe_count && --probe_count == 0)
365 failtest_cleanup(true, 0);
367 if (call == &unrecorded_call)
371 /* + means continue after end, like normal. */
372 if (*failpath == '+')
374 else if (*failpath == '\0') {
375 /* Continue, but don't inject errors. */
376 return call->fail = false;
378 if (tolower((unsigned char)*failpath)
379 != info_to_arg[call->type])
380 errx(1, "Failpath expected '%c' got '%c'\n",
381 info_to_arg[call->type], *failpath);
382 call->fail = isupper((unsigned char)*(failpath++));
387 /* Attach debugger if they asked for it. */
388 if (debugpath && history_num == strlen(debugpath)) {
391 for (i = 0; i < history_num; i++) {
392 unsigned char c = info_to_arg[history[i].type];
395 if (c != debugpath[i])
398 if (i == history_num) {
402 signal(SIGUSR1, SIG_IGN);
403 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
405 if (system(str) == 0)
411 switch (failtest_hook(history, history_num)) {
418 /* Already down probe path? Stop now. */
420 failtest_cleanup(true, 0);
421 /* FIXME: We should run *parent* and run probe until
422 * calls match up again. */
430 files = save_files();
432 /* We're going to fail in the child. */
434 if (pipe(control) != 0 || pipe(output) != 0)
435 err(1, "opening pipe");
437 /* Prevent double-printing (in child and parent) */
441 err(1, "forking failed");
447 gettimeofday(&now, NULL);
448 if (now.tv_usec < start.tv_usec) {
450 now.tv_usec += 1000000;
452 now.tv_usec -= start.tv_usec;
453 now.tv_sec -= start.tv_sec;
454 p = failpath_string();
455 trace("%u->%u (%u.%02u): %s (", getppid(), getpid(),
456 (int)now.tv_sec, (int)now.tv_usec / 10000, p);
458 p = strrchr(history[history_num-1].file, '/');
462 trace("%s", history[history_num-1].file);
463 trace(":%u)\n", history[history_num-1].line);
467 dup2(output[1], STDOUT_FILENO);
468 dup2(output[1], STDERR_FILENO);
469 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
471 control_fd = control[1];
475 signal(SIGUSR1, hand_down);
480 /* We grab output so we can display it; we grab writes so we
483 struct pollfd pfd[2];
486 pfd[0].fd = output[0];
487 pfd[0].events = POLLIN|POLLHUP;
488 pfd[1].fd = control[0];
489 pfd[1].events = POLLIN|POLLHUP;
492 ret = poll(pfd, 1, failtest_timeout_ms);
494 ret = poll(pfd, 2, failtest_timeout_ms);
501 err(1, "Poll returned %i", ret);
504 if (pfd[0].revents & POLLIN) {
507 out = realloc(out, outlen + 8192);
508 len = read(output[0], out + outlen, 8192);
510 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
511 if (read_all(control[0], &type, sizeof(type))) {
513 if (!read_write_info(control[0]))
515 } else if (type == RELEASE_LOCKS) {
517 /* FIXME: Tell them we're done... */
520 } else if (pfd[0].revents & POLLHUP) {
523 } while (type != FAILURE);
527 waitpid(child, &status, 0);
528 if (!WIFEXITED(status)) {
529 if (WTERMSIG(status) == SIGUSR1)
530 child_fail(out, outlen, "Timed out");
532 child_fail(out, outlen, "Killed by signal %u: ",
535 /* Child printed failure already, just pass up exit code. */
536 if (type == FAILURE) {
537 fprintf(stderr, "%.*s", (int)outlen, out);
539 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
541 if (WEXITSTATUS(status) != 0)
542 child_fail(out, outlen, "Exited with status %i: ",
543 WEXITSTATUS(status));
546 signal(SIGUSR1, SIG_DFL);
548 restore_files(files);
550 /* We continue onwards without failing. */
555 static void cleanup_calloc(struct calloc_call *call)
560 void *failtest_calloc(size_t nmemb, size_t size,
561 const char *file, unsigned line)
563 struct failtest_call *p;
564 struct calloc_call call;
567 p = add_history(FAILTEST_CALLOC, file, line, &call);
569 if (should_fail(p)) {
570 p->u.calloc.ret = NULL;
573 p->u.calloc.ret = calloc(nmemb, size);
574 set_cleanup(p, cleanup_calloc, struct calloc_call);
577 return p->u.calloc.ret;
580 static void cleanup_malloc(struct malloc_call *call)
585 void *failtest_malloc(size_t size, const char *file, unsigned line)
587 struct failtest_call *p;
588 struct malloc_call call;
591 p = add_history(FAILTEST_MALLOC, file, line, &call);
592 if (should_fail(p)) {
593 p->u.calloc.ret = NULL;
596 p->u.calloc.ret = malloc(size);
597 set_cleanup(p, cleanup_malloc, struct malloc_call);
600 return p->u.calloc.ret;
603 static void cleanup_realloc(struct realloc_call *call)
608 /* Walk back and find out if we got this ptr from a previous routine. */
609 static void fixup_ptr_history(void *ptr, unsigned int last)
613 /* Start at end of history, work back. */
614 for (i = last - 1; i >= 0; i--) {
615 switch (history[i].type) {
616 case FAILTEST_REALLOC:
617 if (history[i].u.realloc.ret == ptr) {
618 history[i].cleanup = NULL;
622 case FAILTEST_MALLOC:
623 if (history[i].u.malloc.ret == ptr) {
624 history[i].cleanup = NULL;
628 case FAILTEST_CALLOC:
629 if (history[i].u.calloc.ret == ptr) {
630 history[i].cleanup = NULL;
640 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
642 struct failtest_call *p;
643 struct realloc_call call;
645 p = add_history(FAILTEST_REALLOC, file, line, &call);
647 /* FIXME: Try one child moving allocation, one not. */
648 if (should_fail(p)) {
649 p->u.realloc.ret = NULL;
652 fixup_ptr_history(ptr, history_num-1);
653 p->u.realloc.ret = realloc(ptr, size);
654 set_cleanup(p, cleanup_realloc, struct realloc_call);
657 return p->u.realloc.ret;
660 void failtest_free(void *ptr)
662 fixup_ptr_history(ptr, history_num);
666 static void cleanup_open(struct open_call *call)
671 int failtest_open(const char *pathname,
672 const char *file, unsigned line, ...)
674 struct failtest_call *p;
675 struct open_call call;
678 call.pathname = strdup(pathname);
680 call.flags = va_arg(ap, int);
681 if (call.flags & O_CREAT) {
682 call.mode = va_arg(ap, int);
685 p = add_history(FAILTEST_OPEN, file, line, &call);
686 /* Avoid memory leak! */
687 if (p == &unrecorded_call)
688 free((char *)call.pathname);
689 p->u.open.ret = open(pathname, call.flags, call.mode);
691 if (!failpath && p->u.open.ret == -1) {
694 } else if (should_fail(p)) {
695 close(p->u.open.ret);
697 /* FIXME: Play with error codes? */
700 set_cleanup(p, cleanup_open, struct open_call);
703 return p->u.open.ret;
706 static void cleanup_pipe(struct pipe_call *call)
708 if (!call->closed[0])
710 if (!call->closed[1])
714 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
716 struct failtest_call *p;
717 struct pipe_call call;
719 p = add_history(FAILTEST_PIPE, file, line, &call);
720 if (should_fail(p)) {
722 /* FIXME: Play with error codes? */
725 p->u.pipe.ret = pipe(p->u.pipe.fds);
726 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
727 set_cleanup(p, cleanup_pipe, struct pipe_call);
729 /* This causes valgrind to notice if they use pipefd[] after failure */
730 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
732 return p->u.pipe.ret;
735 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
736 const char *file, unsigned line)
738 struct failtest_call *p;
739 struct read_call call;
744 p = add_history(FAILTEST_READ, file, line, &call);
746 /* FIXME: Try partial read returns. */
747 if (should_fail(p)) {
751 p->u.read.ret = pread(fd, buf, count, off);
754 return p->u.read.ret;
757 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
758 const char *file, unsigned line)
760 struct failtest_call *p;
761 struct write_call call;
767 p = add_history(FAILTEST_WRITE, file, line, &call);
769 /* If we're a child, we need to make sure we write the same thing
770 * to non-files as the parent does, so tell it. */
771 if (control_fd != -1 && off == (off_t)-1) {
772 enum info_type type = WRITE;
774 write_all(control_fd, &type, sizeof(type));
775 write_all(control_fd, &p->u.write, sizeof(p->u.write));
776 write_all(control_fd, buf, count);
779 /* FIXME: Try partial write returns. */
780 if (should_fail(p)) {
784 /* FIXME: We assume same write order in parent and child */
785 if (off == (off_t)-1 && child_writes_num != 0) {
786 if (child_writes[0].fd != fd)
787 errx(1, "Child wrote to fd %u, not %u?",
788 child_writes[0].fd, fd);
789 if (child_writes[0].off != p->u.write.off)
790 errx(1, "Child wrote to offset %zu, not %zu?",
791 (size_t)child_writes[0].off,
792 (size_t)p->u.write.off);
793 if (child_writes[0].count != count)
794 errx(1, "Child wrote length %zu, not %zu?",
795 child_writes[0].count, count);
796 if (memcmp(child_writes[0].buf, buf, count)) {
798 "Child wrote differently to"
799 " fd %u than we did!\n", fd);
801 free((char *)child_writes[0].buf);
803 memmove(&child_writes[0], &child_writes[1],
804 sizeof(child_writes[0]) * child_writes_num);
806 /* Is this is a socket or pipe, child wrote it
808 if (p->u.write.off == (off_t)-1) {
809 p->u.write.ret = count;
811 return p->u.write.ret;
814 p->u.write.ret = pwrite(fd, buf, count, off);
817 return p->u.write.ret;
820 ssize_t failtest_read(int fd, void *buf, size_t count,
821 const char *file, unsigned line)
823 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
827 ssize_t failtest_write(int fd, const void *buf, size_t count,
828 const char *file, unsigned line)
830 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
834 static struct lock_info *WARN_UNUSED_RESULT
835 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
840 for (i = 0; i < lock_num; i++) {
845 /* Four cases we care about:
859 if (start > l->start && end < l->end) {
860 /* Mid overlap: trim entry, add new one. */
861 off_t new_start, new_end;
865 locks = add_lock(locks,
866 fd, new_start, new_end, l->type);
868 } else if (start <= l->start && end >= l->end) {
869 /* Total overlap: eliminate entry. */
872 } else if (end >= l->start && end < l->end) {
873 /* Start overlap: trim entry. */
875 } else if (start > l->start && start <= l->end) {
876 /* End overlap: trim entry. */
879 /* Nothing left? Remove it. */
880 if (l->end < l->start) {
881 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
886 if (type != F_UNLCK) {
887 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
888 l = &locks[lock_num++];
897 /* We trap this so we can record it: we don't fail it. */
898 int failtest_close(int fd, const char *file, unsigned line)
901 struct close_call call;
902 struct failtest_call *p;
905 p = add_history(FAILTEST_CLOSE, file, line, &call);
908 /* Consume close from failpath. */
916 /* Trace history to find source of fd. */
917 for (i = history_num-1; i >= 0; i--) {
918 switch (history[i].type) {
921 if (history[i].u.pipe.fds[0] == fd) {
922 assert(!history[i].u.pipe.closed[0]);
923 history[i].u.pipe.closed[0] = true;
924 if (history[i].u.pipe.closed[1])
925 history[i].cleanup = NULL;
928 if (history[i].u.pipe.fds[1] == fd) {
929 assert(!history[i].u.pipe.closed[1]);
930 history[i].u.pipe.closed[1] = true;
931 if (history[i].u.pipe.closed[0])
932 history[i].cleanup = NULL;
937 if (history[i].u.open.ret == fd) {
938 assert((void *)history[i].cleanup
939 == (void *)cleanup_open);
940 history[i].cleanup = NULL;
950 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
954 /* Zero length means "to end of file" */
955 static off_t end_of(off_t start, off_t len)
959 return start + len - 1;
962 /* FIXME: This only handles locks, really. */
963 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
965 struct failtest_call *p;
966 struct fcntl_call call;
972 /* Argument extraction. */
977 call.arg.l = va_arg(ap, long);
979 return fcntl(fd, cmd, call.arg.l);
982 return fcntl(fd, cmd);
986 call.arg.fl = *va_arg(ap, struct flock *);
988 return fcntl(fd, cmd, &call.arg.fl);
992 call.arg.fl = *va_arg(ap, struct flock *);
996 /* This means you need to implement it here. */
997 err(1, "failtest: unknown fcntl %u", cmd);
1000 p = add_history(FAILTEST_FCNTL, file, line, &call);
1002 if (should_fail(p)) {
1003 p->u.fcntl.ret = -1;
1004 if (p->u.fcntl.cmd == F_SETLK)
1010 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
1011 &p->u.fcntl.arg.fl);
1012 if (p->u.fcntl.ret == -1)
1015 /* We don't handle anything else yet. */
1016 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1017 locks = add_lock(locks,
1019 p->u.fcntl.arg.fl.l_start,
1020 end_of(p->u.fcntl.arg.fl.l_start,
1021 p->u.fcntl.arg.fl.l_len),
1022 p->u.fcntl.arg.fl.l_type);
1026 return p->u.fcntl.ret;
1029 pid_t failtest_getpid(const char *file, unsigned line)
1031 /* You must call failtest_init first! */
1036 void failtest_init(int argc, char *argv[])
1040 orig_pid = getpid();
1042 for (i = 1; i < argc; i++) {
1043 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1044 failpath = argv[i] + strlen("--failpath=");
1045 } else if (strcmp(argv[i], "--tracepath") == 0) {
1046 tracefd = dup(STDERR_FILENO);
1047 failtest_timeout_ms = -1;
1048 } else if (!strncmp(argv[i], "--debugpath=",
1049 strlen("--debugpath="))) {
1050 debugpath = argv[i] + strlen("--debugpath=");
1053 gettimeofday(&start, NULL);
1056 bool failtest_has_failed(void)
1058 return control_fd != -1;
1061 void failtest_exit(int status)
1063 if (failtest_exit_check) {
1064 if (!failtest_exit_check(history, history_num))
1065 child_fail(NULL, 0, "failtest_exit_check failed\n");
1068 failtest_cleanup(false, status);