1 /* Licensed under LGPL - see LICENSE file for details */
2 #include <ccan/failtest/failtest.h>
12 #include <sys/types.h>
18 #include <ccan/time/time.h>
19 #include <ccan/read_write_all/read_write_all.h>
20 #include <ccan/failtest/failtest_proto.h>
21 #include <ccan/build_assert/build_assert.h>
22 #include <ccan/str/str.h>
24 enum failtest_result (*failtest_hook)(struct tlist_calls *);
26 static int tracefd = -1;
29 unsigned int failtest_timeout_ms = 20000;
32 const char *debugpath;
44 /* end is inclusive: you can't have a 0-byte lock. */
49 bool (*failtest_exit_check)(struct tlist_calls *history);
51 static struct tlist_calls history = TLIST_INIT(history);
52 static int control_fd = -1;
53 static struct timeval start;
54 static unsigned int probe_count = 0;
56 static struct write_call *child_writes = NULL;
57 static unsigned int child_writes_num = 0;
59 static pid_t lock_owner;
60 static struct lock_info *locks = NULL;
61 static unsigned int lock_num = 0;
63 static pid_t orig_pid;
65 static const char info_to_arg[] = "mceoxprwf";
67 /* Dummy call used for failtest_undo wrappers. */
68 static struct failtest_call unrecorded_call;
70 static struct failtest_call *add_history_(enum failtest_call_type type,
76 struct failtest_call *call;
78 /* NULL file is how we suppress failure. */
80 return &unrecorded_call;
82 call = malloc(sizeof *call);
87 memcpy(&call->u, elem, elem_size);
88 tlist_add_tail(&history, call, list);
92 #define add_history(type, file, line, elem) \
93 add_history_((type), (file), (line), (elem), sizeof(*(elem)))
95 /* We do a fake call inside a sizeof(), to check types. */
96 #define set_cleanup(call, clean, type) \
97 (call)->cleanup = (void *)((void)sizeof(clean((type *)NULL),1), (clean))
100 /* Dup the fd to a high value (out of the way I hope!), and close the old fd. */
101 static int move_fd_to_high(int fd)
105 for (i = FD_SETSIZE - 1; i >= 0; i--) {
106 if (fcntl(i, F_GETFL) == -1 && errno == EBADF) {
107 if (dup2(fd, i) == -1)
108 err(1, "Failed to dup fd %i to %i", fd, i);
113 /* Nothing? Really? Er... ok? */
117 static bool read_write_info(int fd)
119 struct write_call *w;
122 /* We don't need all of this, but it's simple. */
123 child_writes = realloc(child_writes,
124 (child_writes_num+1) * sizeof(child_writes[0]));
125 w = &child_writes[child_writes_num];
126 if (!read_all(fd, w, sizeof(*w)))
129 w->buf = buf = malloc(w->count);
130 if (!read_all(fd, buf, w->count))
137 static char *failpath_string(void)
139 struct failtest_call *i;
140 char *ret = strdup("");
143 /* Inefficient, but who cares? */
144 tlist_for_each(&history, i, list) {
145 ret = realloc(ret, len + 2);
146 ret[len] = info_to_arg[i->type];
148 ret[len] = toupper(ret[len]);
154 static void warn_via_fd(int e, const char *fmt, va_list ap)
156 char *p = failpath_string();
158 vdprintf(warnfd, fmt, ap);
160 dprintf(warnfd, ": %s", strerror(e));
161 dprintf(warnfd, " [%s]\n", p);
165 static void fwarn(const char *fmt, ...)
171 warn_via_fd(e, fmt, ap);
176 static void fwarnx(const char *fmt, ...)
181 warn_via_fd(-1, fmt, ap);
185 static void tell_parent(enum info_type type)
187 if (control_fd != -1)
188 write_all(control_fd, &type, sizeof(type));
191 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
194 char *path = failpath_string();
197 vfprintf(stderr, fmt, ap);
200 fprintf(stderr, "%.*s", (int)outlen, out);
201 printf("To reproduce: --failpath=%s\n", path);
203 tell_parent(FAILURE);
207 static void trace(const char *fmt, ...)
215 vdprintf(tracefd, fmt, ap);
221 static void hand_down(int signum)
226 static void release_locks(void)
228 /* Locks were never acquired/reacquired? */
232 /* We own them? Release them all. */
233 if (lock_owner == getpid()) {
237 fl.l_whence = SEEK_SET;
241 for (i = 0; i < lock_num; i++)
242 fcntl(locks[i].fd, F_SETLK, &fl);
244 /* Our parent must have them; pass request up. */
245 enum info_type type = RELEASE_LOCKS;
246 assert(control_fd != -1);
247 write_all(control_fd, &type, sizeof(type));
252 /* off_t is a signed type. Getting its max is non-trivial. */
253 static off_t off_max(void)
255 BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
256 if (sizeof(off_t) == 4)
257 return (off_t)0x7FFFFFF;
259 return (off_t)0x7FFFFFFFFFFFFFFULL;
262 static void get_locks(void)
267 if (lock_owner == getpid())
270 if (lock_owner != 0) {
271 enum info_type type = RELEASE_LOCKS;
272 assert(control_fd != -1);
273 write_all(control_fd, &type, sizeof(type));
276 fl.l_whence = SEEK_SET;
278 for (i = 0; i < lock_num; i++) {
279 fl.l_type = locks[i].type;
280 fl.l_start = locks[i].start;
281 if (locks[i].end == off_max())
284 fl.l_len = locks[i].end - locks[i].start + 1;
286 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
289 lock_owner = getpid();
293 struct saved_file *next;
299 static struct saved_file *save_file(struct saved_file *next, int fd)
301 struct saved_file *s = malloc(sizeof(*s));
305 s->off = lseek(fd, 0, SEEK_CUR);
306 /* Special file? Erk... */
307 assert(s->off != -1);
308 s->len = lseek(fd, 0, SEEK_END);
309 lseek(fd, 0, SEEK_SET);
310 s->contents = malloc(s->len);
311 if (read(fd, s->contents, s->len) != s->len)
312 err(1, "Failed to save %zu bytes", (size_t)s->len);
313 lseek(fd, s->off, SEEK_SET);
317 /* We have little choice but to save and restore open files: mmap means we
318 * can really intercept changes in the child.
320 * We could do non-mmap'ed files on demand, however. */
321 static struct saved_file *save_files(void)
323 struct saved_file *files = NULL;
324 struct failtest_call *i;
326 /* Figure out the set of live fds. */
327 tlist_for_each_rev(&history, i, list) {
328 if (i->type == FAILTEST_OPEN) {
329 int fd = i->u.open.ret;
330 /* Only do successful, writable fds. */
334 /* If it was closed, cleanup == NULL. */
338 if ((i->u.open.flags & O_RDWR) == O_RDWR) {
339 files = save_file(files, fd);
340 } else if ((i->u.open.flags & O_WRONLY)
342 /* FIXME: Handle O_WRONLY. Open with O_RDWR? */
351 static void restore_files(struct saved_file *s)
354 struct saved_file *next = s->next;
356 lseek(s->fd, 0, SEEK_SET);
357 if (write(s->fd, s->contents, s->len) != s->len)
358 err(1, "Failed to restore %zu bytes", (size_t)s->len);
359 if (ftruncate(s->fd, s->len) != 0)
360 err(1, "Failed to trim file to length %zu",
363 lseek(s->fd, s->off, SEEK_SET);
369 static void free_files(struct saved_file *s)
372 struct saved_file *next = s->next;
379 static void free_call(struct failtest_call *call)
381 /* We don't do this in cleanup: needed even for failed opens. */
382 if (call->type == FAILTEST_OPEN)
383 free((char *)call->u.open.pathname);
384 tlist_del_from(&history, call, list);
388 /* Free up memory, so valgrind doesn't report leaks. */
389 static void free_everything(void)
391 struct failtest_call *i;
393 while ((i = tlist_top(&history, struct failtest_call, list)) != NULL)
397 static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
399 struct failtest_call *i;
401 /* For children, we don't care if they "failed" the testing. */
402 if (control_fd != -1)
405 if (forced_cleanup) {
406 /* We didn't actually do final operation: remove it. */
407 i = tlist_tail(&history, struct failtest_call, list);
411 /* Cleanup everything, in reverse order. */
412 tlist_for_each_rev(&history, i, list) {
415 if (!forced_cleanup) {
416 printf("Leak at %s:%u: --failpath=%s\n",
417 i->file, i->line, failpath_string());
424 tell_parent(SUCCESS);
428 static bool should_fail(struct failtest_call *call)
431 int control[2], output[2];
432 enum info_type type = UNEXPECTED;
435 struct saved_file *files;
437 /* Are we probing? */
438 if (probe_count && --probe_count == 0 && control_fd != -1)
439 failtest_cleanup(true, 0);
441 if (call == &unrecorded_call)
445 /* + means continue after end, like normal. */
446 if (*failpath == '+')
448 else if (*failpath == '\0') {
449 /* Continue, but don't inject errors. */
450 return call->fail = false;
452 if (tolower((unsigned char)*failpath)
453 != info_to_arg[call->type])
454 errx(1, "Failpath expected '%c' got '%c'\n",
455 info_to_arg[call->type], *failpath);
456 call->fail = cisupper(*(failpath++));
461 /* Attach debugger if they asked for it. */
463 char *path = failpath_string();
465 if (streq(path, debugpath)) {
469 signal(SIGUSR1, SIG_IGN);
470 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
472 if (system(str) == 0)
474 } else if (!strstarts(path, debugpath)) {
475 fprintf(stderr, "--debugpath not followed: %s\n", path);
482 switch (failtest_hook(&history)) {
486 /* Already down probe path? Stop now. */
488 /* FIXME: We should run *parent* and
489 * run probe until calls match up again. */
493 /* Child should give up now. */
494 if (control_fd != -1)
495 failtest_cleanup(true, 0);
496 /* Parent, don't fail again. */
506 files = save_files();
508 /* We're going to fail in the child. */
510 if (pipe(control) != 0 || pipe(output) != 0)
511 err(1, "opening pipe");
513 /* Prevent double-printing (in child and parent) */
517 err(1, "forking failed");
524 struct failtest_call *c;
526 c = tlist_tail(&history, struct failtest_call, list);
527 diff = time_sub(time_now(), start);
528 failpath = failpath_string();
529 trace("%u->%u (%u.%02u): %s (", getppid(), getpid(),
530 (int)diff.tv_sec, (int)diff.tv_usec / 10000,
533 p = strrchr(c->file, '/');
537 trace("%s", c->file);
538 trace(":%u)\n", c->line);
542 dup2(output[1], STDOUT_FILENO);
543 dup2(output[1], STDERR_FILENO);
544 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
546 control_fd = move_fd_to_high(control[1]);
547 /* Valgrind spots the leak if we don't free these. */
552 signal(SIGUSR1, hand_down);
557 /* We grab output so we can display it; we grab writes so we
560 struct pollfd pfd[2];
563 pfd[0].fd = output[0];
564 pfd[0].events = POLLIN|POLLHUP;
565 pfd[1].fd = control[0];
566 pfd[1].events = POLLIN|POLLHUP;
569 ret = poll(pfd, 1, failtest_timeout_ms);
571 ret = poll(pfd, 2, failtest_timeout_ms);
578 err(1, "Poll returned %i", ret);
581 if (pfd[0].revents & POLLIN) {
584 out = realloc(out, outlen + 8192);
585 len = read(output[0], out + outlen, 8192);
587 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
588 if (read_all(control[0], &type, sizeof(type))) {
590 if (!read_write_info(control[0]))
592 } else if (type == RELEASE_LOCKS) {
594 /* FIXME: Tell them we're done... */
597 } else if (pfd[0].revents & POLLHUP) {
600 } while (type != FAILURE);
604 waitpid(child, &status, 0);
605 if (!WIFEXITED(status)) {
606 if (WTERMSIG(status) == SIGUSR1)
607 child_fail(out, outlen, "Timed out");
609 child_fail(out, outlen, "Killed by signal %u: ",
612 /* Child printed failure already, just pass up exit code. */
613 if (type == FAILURE) {
614 fprintf(stderr, "%.*s", (int)outlen, out);
616 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
618 if (WEXITSTATUS(status) != 0)
619 child_fail(out, outlen, "Exited with status %i: ",
620 WEXITSTATUS(status));
623 signal(SIGUSR1, SIG_DFL);
625 restore_files(files);
627 /* We continue onwards without failing. */
632 static void cleanup_calloc(struct calloc_call *call)
637 void *failtest_calloc(size_t nmemb, size_t size,
638 const char *file, unsigned line)
640 struct failtest_call *p;
641 struct calloc_call call;
644 p = add_history(FAILTEST_CALLOC, file, line, &call);
646 if (should_fail(p)) {
647 p->u.calloc.ret = NULL;
650 p->u.calloc.ret = calloc(nmemb, size);
651 set_cleanup(p, cleanup_calloc, struct calloc_call);
654 return p->u.calloc.ret;
657 static void cleanup_malloc(struct malloc_call *call)
662 void *failtest_malloc(size_t size, const char *file, unsigned line)
664 struct failtest_call *p;
665 struct malloc_call call;
668 p = add_history(FAILTEST_MALLOC, file, line, &call);
669 if (should_fail(p)) {
670 p->u.malloc.ret = NULL;
673 p->u.malloc.ret = malloc(size);
674 set_cleanup(p, cleanup_malloc, struct malloc_call);
677 return p->u.malloc.ret;
680 static void cleanup_realloc(struct realloc_call *call)
685 /* Walk back and find out if we got this ptr from a previous routine. */
686 static void fixup_ptr_history(void *ptr)
688 struct failtest_call *i;
690 /* Start at end of history, work back. */
691 tlist_for_each_rev(&history, i, list) {
693 case FAILTEST_REALLOC:
694 if (i->u.realloc.ret == ptr) {
699 case FAILTEST_MALLOC:
700 if (i->u.malloc.ret == ptr) {
705 case FAILTEST_CALLOC:
706 if (i->u.calloc.ret == ptr) {
717 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
719 struct failtest_call *p;
720 struct realloc_call call;
722 p = add_history(FAILTEST_REALLOC, file, line, &call);
724 /* FIXME: Try one child moving allocation, one not. */
725 if (should_fail(p)) {
726 p->u.realloc.ret = NULL;
729 /* Don't catch this one in the history fixup... */
730 p->u.realloc.ret = NULL;
731 fixup_ptr_history(ptr);
732 p->u.realloc.ret = realloc(ptr, size);
733 set_cleanup(p, cleanup_realloc, struct realloc_call);
736 return p->u.realloc.ret;
739 void failtest_free(void *ptr)
741 fixup_ptr_history(ptr);
745 static void cleanup_open(struct open_call *call)
750 int failtest_open(const char *pathname,
751 const char *file, unsigned line, ...)
753 struct failtest_call *p;
754 struct open_call call;
757 call.pathname = strdup(pathname);
759 call.flags = va_arg(ap, int);
760 if (call.flags & O_CREAT) {
761 call.mode = va_arg(ap, int);
764 p = add_history(FAILTEST_OPEN, file, line, &call);
765 /* Avoid memory leak! */
766 if (p == &unrecorded_call)
767 free((char *)call.pathname);
768 p->u.open.ret = open(pathname, call.flags, call.mode);
770 if (p->u.open.ret == -1) {
773 } else if (should_fail(p)) {
774 close(p->u.open.ret);
776 /* FIXME: Play with error codes? */
779 set_cleanup(p, cleanup_open, struct open_call);
782 return p->u.open.ret;
785 static void cleanup_pipe(struct pipe_call *call)
787 if (!call->closed[0])
789 if (!call->closed[1])
793 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
795 struct failtest_call *p;
796 struct pipe_call call;
798 p = add_history(FAILTEST_PIPE, file, line, &call);
799 if (should_fail(p)) {
801 /* FIXME: Play with error codes? */
804 p->u.pipe.ret = pipe(p->u.pipe.fds);
805 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
806 set_cleanup(p, cleanup_pipe, struct pipe_call);
808 /* This causes valgrind to notice if they use pipefd[] after failure */
809 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
811 return p->u.pipe.ret;
814 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
815 const char *file, unsigned line)
817 struct failtest_call *p;
818 struct read_call call;
823 p = add_history(FAILTEST_READ, file, line, &call);
825 /* FIXME: Try partial read returns. */
826 if (should_fail(p)) {
830 p->u.read.ret = pread(fd, buf, count, off);
833 return p->u.read.ret;
836 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
837 const char *file, unsigned line)
839 struct failtest_call *p;
840 struct write_call call;
846 p = add_history(FAILTEST_WRITE, file, line, &call);
848 /* If we're a child, we need to make sure we write the same thing
849 * to non-files as the parent does, so tell it. */
850 if (control_fd != -1 && off == (off_t)-1) {
851 enum info_type type = WRITE;
853 write_all(control_fd, &type, sizeof(type));
854 write_all(control_fd, &p->u.write, sizeof(p->u.write));
855 write_all(control_fd, buf, count);
858 /* FIXME: Try partial write returns. */
859 if (should_fail(p)) {
863 /* FIXME: We assume same write order in parent and child */
864 if (off == (off_t)-1 && child_writes_num != 0) {
865 if (child_writes[0].fd != fd)
866 errx(1, "Child wrote to fd %u, not %u?",
867 child_writes[0].fd, fd);
868 if (child_writes[0].off != p->u.write.off)
869 errx(1, "Child wrote to offset %zu, not %zu?",
870 (size_t)child_writes[0].off,
871 (size_t)p->u.write.off);
872 if (child_writes[0].count != count)
873 errx(1, "Child wrote length %zu, not %zu?",
874 child_writes[0].count, count);
875 if (memcmp(child_writes[0].buf, buf, count)) {
877 "Child wrote differently to"
878 " fd %u than we did!\n", fd);
880 free((char *)child_writes[0].buf);
882 memmove(&child_writes[0], &child_writes[1],
883 sizeof(child_writes[0]) * child_writes_num);
885 /* Is this is a socket or pipe, child wrote it
887 if (p->u.write.off == (off_t)-1) {
888 p->u.write.ret = count;
890 return p->u.write.ret;
893 p->u.write.ret = pwrite(fd, buf, count, off);
896 return p->u.write.ret;
899 ssize_t failtest_read(int fd, void *buf, size_t count,
900 const char *file, unsigned line)
902 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
906 ssize_t failtest_write(int fd, const void *buf, size_t count,
907 const char *file, unsigned line)
909 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
913 static struct lock_info *WARN_UNUSED_RESULT
914 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
919 for (i = 0; i < lock_num; i++) {
924 /* Four cases we care about:
938 if (start > l->start && end < l->end) {
939 /* Mid overlap: trim entry, add new one. */
940 off_t new_start, new_end;
944 locks = add_lock(locks,
945 fd, new_start, new_end, l->type);
947 } else if (start <= l->start && end >= l->end) {
948 /* Total overlap: eliminate entry. */
951 } else if (end >= l->start && end < l->end) {
952 /* Start overlap: trim entry. */
954 } else if (start > l->start && start <= l->end) {
955 /* End overlap: trim entry. */
958 /* Nothing left? Remove it. */
959 if (l->end < l->start) {
960 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
965 if (type != F_UNLCK) {
966 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
967 l = &locks[lock_num++];
976 /* We trap this so we can record it: we don't fail it. */
977 int failtest_close(int fd, const char *file, unsigned line)
979 struct failtest_call *i;
980 struct close_call call;
981 struct failtest_call *p;
984 p = add_history(FAILTEST_CLOSE, file, line, &call);
987 /* Consume close from failpath. */
995 /* Trace history to find source of fd. */
996 tlist_for_each_rev(&history, i, list) {
1000 if (i->u.pipe.fds[0] == fd) {
1001 assert(!i->u.pipe.closed[0]);
1002 i->u.pipe.closed[0] = true;
1003 if (i->u.pipe.closed[1])
1007 if (i->u.pipe.fds[1] == fd) {
1008 assert(!i->u.pipe.closed[1]);
1009 i->u.pipe.closed[1] = true;
1010 if (i->u.pipe.closed[0])
1016 if (i->u.open.ret == fd) {
1017 assert((void *)i->cleanup
1018 == (void *)cleanup_open);
1029 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
1033 /* Zero length means "to end of file" */
1034 static off_t end_of(off_t start, off_t len)
1038 return start + len - 1;
1041 /* FIXME: This only handles locks, really. */
1042 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
1044 struct failtest_call *p;
1045 struct fcntl_call call;
1051 /* Argument extraction. */
1056 call.arg.l = va_arg(ap, long);
1058 return fcntl(fd, cmd, call.arg.l);
1061 return fcntl(fd, cmd);
1065 call.arg.fl = *va_arg(ap, struct flock *);
1067 return fcntl(fd, cmd, &call.arg.fl);
1071 call.arg.fl = *va_arg(ap, struct flock *);
1075 /* This means you need to implement it here. */
1076 err(1, "failtest: unknown fcntl %u", cmd);
1079 p = add_history(FAILTEST_FCNTL, file, line, &call);
1081 if (should_fail(p)) {
1082 p->u.fcntl.ret = -1;
1083 if (p->u.fcntl.cmd == F_SETLK)
1089 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
1090 &p->u.fcntl.arg.fl);
1091 if (p->u.fcntl.ret == -1)
1094 /* We don't handle anything else yet. */
1095 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1096 locks = add_lock(locks,
1098 p->u.fcntl.arg.fl.l_start,
1099 end_of(p->u.fcntl.arg.fl.l_start,
1100 p->u.fcntl.arg.fl.l_len),
1101 p->u.fcntl.arg.fl.l_type);
1105 return p->u.fcntl.ret;
1108 pid_t failtest_getpid(const char *file, unsigned line)
1110 /* You must call failtest_init first! */
1115 void failtest_init(int argc, char *argv[])
1119 orig_pid = getpid();
1121 warnfd = move_fd_to_high(dup(STDERR_FILENO));
1122 for (i = 1; i < argc; i++) {
1123 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1124 failpath = argv[i] + strlen("--failpath=");
1125 } else if (strcmp(argv[i], "--tracepath") == 0) {
1127 failtest_timeout_ms = -1;
1128 } else if (!strncmp(argv[i], "--debugpath=",
1129 strlen("--debugpath="))) {
1130 debugpath = argv[i] + strlen("--debugpath=");
1136 bool failtest_has_failed(void)
1138 return control_fd != -1;
1141 void failtest_exit(int status)
1143 if (failtest_exit_check) {
1144 if (!failtest_exit_check(&history))
1145 child_fail(NULL, 0, "failtest_exit_check failed\n");
1148 failtest_cleanup(false, status);