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 bool probing = false;
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 if (call == &unrecorded_call)
441 /* + means continue after end, like normal. */
442 if (*failpath == '+')
444 else if (*failpath == '\0') {
445 /* Continue, but don't inject errors. */
446 return call->fail = false;
448 if (tolower((unsigned char)*failpath)
449 != info_to_arg[call->type])
450 errx(1, "Failpath expected '%c' got '%c'\n",
451 info_to_arg[call->type], *failpath);
452 call->fail = cisupper(*(failpath++));
457 /* Attach debugger if they asked for it. */
459 char *path = failpath_string();
461 if (streq(path, debugpath)) {
465 signal(SIGUSR1, SIG_IGN);
466 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
468 if (system(str) == 0)
470 } else if (!strstarts(path, debugpath)) {
471 fprintf(stderr, "--debugpath not followed: %s\n", path);
477 /* Are we probing? If so, we never fail twice. */
479 return call->fail = false;
482 switch (failtest_hook(&history)) {
496 files = save_files();
498 /* We're going to fail in the child. */
500 if (pipe(control) != 0 || pipe(output) != 0)
501 err(1, "opening pipe");
503 /* Prevent double-printing (in child and parent) */
507 err(1, "forking failed");
514 struct failtest_call *c;
516 c = tlist_tail(&history, struct failtest_call, list);
517 diff = time_sub(time_now(), start);
518 failpath = failpath_string();
519 trace("%u->%u (%u.%02u): %s (", getppid(), getpid(),
520 (int)diff.tv_sec, (int)diff.tv_usec / 10000,
523 p = strrchr(c->file, '/');
527 trace("%s", c->file);
528 trace(":%u)\n", c->line);
532 dup2(output[1], STDOUT_FILENO);
533 dup2(output[1], STDERR_FILENO);
534 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
536 control_fd = move_fd_to_high(control[1]);
537 /* Valgrind spots the leak if we don't free these. */
542 signal(SIGUSR1, hand_down);
547 /* We grab output so we can display it; we grab writes so we
550 struct pollfd pfd[2];
553 pfd[0].fd = output[0];
554 pfd[0].events = POLLIN|POLLHUP;
555 pfd[1].fd = control[0];
556 pfd[1].events = POLLIN|POLLHUP;
559 ret = poll(pfd, 1, failtest_timeout_ms);
561 ret = poll(pfd, 2, failtest_timeout_ms);
568 err(1, "Poll returned %i", ret);
571 if (pfd[0].revents & POLLIN) {
574 out = realloc(out, outlen + 8192);
575 len = read(output[0], out + outlen, 8192);
577 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
578 if (read_all(control[0], &type, sizeof(type))) {
580 if (!read_write_info(control[0]))
582 } else if (type == RELEASE_LOCKS) {
584 /* FIXME: Tell them we're done... */
587 } else if (pfd[0].revents & POLLHUP) {
590 } while (type != FAILURE);
594 waitpid(child, &status, 0);
595 if (!WIFEXITED(status)) {
596 if (WTERMSIG(status) == SIGUSR1)
597 child_fail(out, outlen, "Timed out");
599 child_fail(out, outlen, "Killed by signal %u: ",
602 /* Child printed failure already, just pass up exit code. */
603 if (type == FAILURE) {
604 fprintf(stderr, "%.*s", (int)outlen, out);
606 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
608 if (WEXITSTATUS(status) != 0)
609 child_fail(out, outlen, "Exited with status %i: ",
610 WEXITSTATUS(status));
613 signal(SIGUSR1, SIG_DFL);
615 restore_files(files);
617 /* Only child does probe. */
620 /* We continue onwards without failing. */
625 static void cleanup_calloc(struct calloc_call *call)
630 void *failtest_calloc(size_t nmemb, size_t size,
631 const char *file, unsigned line)
633 struct failtest_call *p;
634 struct calloc_call call;
637 p = add_history(FAILTEST_CALLOC, file, line, &call);
639 if (should_fail(p)) {
640 p->u.calloc.ret = NULL;
643 p->u.calloc.ret = calloc(nmemb, size);
644 set_cleanup(p, cleanup_calloc, struct calloc_call);
647 return p->u.calloc.ret;
650 static void cleanup_malloc(struct malloc_call *call)
655 void *failtest_malloc(size_t size, const char *file, unsigned line)
657 struct failtest_call *p;
658 struct malloc_call call;
661 p = add_history(FAILTEST_MALLOC, file, line, &call);
662 if (should_fail(p)) {
663 p->u.malloc.ret = NULL;
666 p->u.malloc.ret = malloc(size);
667 set_cleanup(p, cleanup_malloc, struct malloc_call);
670 return p->u.malloc.ret;
673 static void cleanup_realloc(struct realloc_call *call)
678 /* Walk back and find out if we got this ptr from a previous routine. */
679 static void fixup_ptr_history(void *ptr)
681 struct failtest_call *i;
683 /* Start at end of history, work back. */
684 tlist_for_each_rev(&history, i, list) {
686 case FAILTEST_REALLOC:
687 if (i->u.realloc.ret == ptr) {
692 case FAILTEST_MALLOC:
693 if (i->u.malloc.ret == ptr) {
698 case FAILTEST_CALLOC:
699 if (i->u.calloc.ret == ptr) {
710 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
712 struct failtest_call *p;
713 struct realloc_call call;
715 p = add_history(FAILTEST_REALLOC, file, line, &call);
717 /* FIXME: Try one child moving allocation, one not. */
718 if (should_fail(p)) {
719 p->u.realloc.ret = NULL;
722 /* Don't catch this one in the history fixup... */
723 p->u.realloc.ret = NULL;
724 fixup_ptr_history(ptr);
725 p->u.realloc.ret = realloc(ptr, size);
726 set_cleanup(p, cleanup_realloc, struct realloc_call);
729 return p->u.realloc.ret;
732 void failtest_free(void *ptr)
734 fixup_ptr_history(ptr);
738 static void cleanup_open(struct open_call *call)
743 int failtest_open(const char *pathname,
744 const char *file, unsigned line, ...)
746 struct failtest_call *p;
747 struct open_call call;
750 call.pathname = strdup(pathname);
752 call.flags = va_arg(ap, int);
753 if (call.flags & O_CREAT) {
754 call.mode = va_arg(ap, int);
757 p = add_history(FAILTEST_OPEN, file, line, &call);
758 /* Avoid memory leak! */
759 if (p == &unrecorded_call)
760 free((char *)call.pathname);
761 p->u.open.ret = open(pathname, call.flags, call.mode);
763 if (p->u.open.ret == -1) {
766 } else if (should_fail(p)) {
767 close(p->u.open.ret);
769 /* FIXME: Play with error codes? */
772 set_cleanup(p, cleanup_open, struct open_call);
775 return p->u.open.ret;
778 static void cleanup_pipe(struct pipe_call *call)
780 if (!call->closed[0])
782 if (!call->closed[1])
786 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
788 struct failtest_call *p;
789 struct pipe_call call;
791 p = add_history(FAILTEST_PIPE, file, line, &call);
792 if (should_fail(p)) {
794 /* FIXME: Play with error codes? */
797 p->u.pipe.ret = pipe(p->u.pipe.fds);
798 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
799 set_cleanup(p, cleanup_pipe, struct pipe_call);
801 /* This causes valgrind to notice if they use pipefd[] after failure */
802 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
804 return p->u.pipe.ret;
807 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
808 const char *file, unsigned line)
810 struct failtest_call *p;
811 struct read_call call;
816 p = add_history(FAILTEST_READ, file, line, &call);
818 /* FIXME: Try partial read returns. */
819 if (should_fail(p)) {
823 p->u.read.ret = pread(fd, buf, count, off);
826 return p->u.read.ret;
829 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
830 const char *file, unsigned line)
832 struct failtest_call *p;
833 struct write_call call;
839 p = add_history(FAILTEST_WRITE, file, line, &call);
841 /* If we're a child, we need to make sure we write the same thing
842 * to non-files as the parent does, so tell it. */
843 if (control_fd != -1 && off == (off_t)-1) {
844 enum info_type type = WRITE;
846 write_all(control_fd, &type, sizeof(type));
847 write_all(control_fd, &p->u.write, sizeof(p->u.write));
848 write_all(control_fd, buf, count);
851 /* FIXME: Try partial write returns. */
852 if (should_fail(p)) {
856 /* FIXME: We assume same write order in parent and child */
857 if (off == (off_t)-1 && child_writes_num != 0) {
858 if (child_writes[0].fd != fd)
859 errx(1, "Child wrote to fd %u, not %u?",
860 child_writes[0].fd, fd);
861 if (child_writes[0].off != p->u.write.off)
862 errx(1, "Child wrote to offset %zu, not %zu?",
863 (size_t)child_writes[0].off,
864 (size_t)p->u.write.off);
865 if (child_writes[0].count != count)
866 errx(1, "Child wrote length %zu, not %zu?",
867 child_writes[0].count, count);
868 if (memcmp(child_writes[0].buf, buf, count)) {
870 "Child wrote differently to"
871 " fd %u than we did!\n", fd);
873 free((char *)child_writes[0].buf);
875 memmove(&child_writes[0], &child_writes[1],
876 sizeof(child_writes[0]) * child_writes_num);
878 /* Is this is a socket or pipe, child wrote it
880 if (p->u.write.off == (off_t)-1) {
881 p->u.write.ret = count;
883 return p->u.write.ret;
886 p->u.write.ret = pwrite(fd, buf, count, off);
889 return p->u.write.ret;
892 ssize_t failtest_read(int fd, void *buf, size_t count,
893 const char *file, unsigned line)
895 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
899 ssize_t failtest_write(int fd, const void *buf, size_t count,
900 const char *file, unsigned line)
902 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
906 static struct lock_info *WARN_UNUSED_RESULT
907 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
912 for (i = 0; i < lock_num; i++) {
917 /* Four cases we care about:
931 if (start > l->start && end < l->end) {
932 /* Mid overlap: trim entry, add new one. */
933 off_t new_start, new_end;
937 locks = add_lock(locks,
938 fd, new_start, new_end, l->type);
940 } else if (start <= l->start && end >= l->end) {
941 /* Total overlap: eliminate entry. */
944 } else if (end >= l->start && end < l->end) {
945 /* Start overlap: trim entry. */
947 } else if (start > l->start && start <= l->end) {
948 /* End overlap: trim entry. */
951 /* Nothing left? Remove it. */
952 if (l->end < l->start) {
953 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
958 if (type != F_UNLCK) {
959 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
960 l = &locks[lock_num++];
969 /* We trap this so we can record it: we don't fail it. */
970 int failtest_close(int fd, const char *file, unsigned line)
972 struct failtest_call *i;
973 struct close_call call;
974 struct failtest_call *p;
977 p = add_history(FAILTEST_CLOSE, file, line, &call);
980 /* Consume close from failpath. */
988 /* Trace history to find source of fd. */
989 tlist_for_each_rev(&history, i, list) {
993 if (i->u.pipe.fds[0] == fd) {
994 assert(!i->u.pipe.closed[0]);
995 i->u.pipe.closed[0] = true;
996 if (i->u.pipe.closed[1])
1000 if (i->u.pipe.fds[1] == fd) {
1001 assert(!i->u.pipe.closed[1]);
1002 i->u.pipe.closed[1] = true;
1003 if (i->u.pipe.closed[0])
1009 if (i->u.open.ret == fd) {
1010 assert((void *)i->cleanup
1011 == (void *)cleanup_open);
1022 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
1026 /* Zero length means "to end of file" */
1027 static off_t end_of(off_t start, off_t len)
1031 return start + len - 1;
1034 /* FIXME: This only handles locks, really. */
1035 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
1037 struct failtest_call *p;
1038 struct fcntl_call call;
1044 /* Argument extraction. */
1049 call.arg.l = va_arg(ap, long);
1051 return fcntl(fd, cmd, call.arg.l);
1054 return fcntl(fd, cmd);
1058 call.arg.fl = *va_arg(ap, struct flock *);
1060 return fcntl(fd, cmd, &call.arg.fl);
1064 call.arg.fl = *va_arg(ap, struct flock *);
1068 /* This means you need to implement it here. */
1069 err(1, "failtest: unknown fcntl %u", cmd);
1072 p = add_history(FAILTEST_FCNTL, file, line, &call);
1074 if (should_fail(p)) {
1075 p->u.fcntl.ret = -1;
1076 if (p->u.fcntl.cmd == F_SETLK)
1082 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
1083 &p->u.fcntl.arg.fl);
1084 if (p->u.fcntl.ret == -1)
1087 /* We don't handle anything else yet. */
1088 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1089 locks = add_lock(locks,
1091 p->u.fcntl.arg.fl.l_start,
1092 end_of(p->u.fcntl.arg.fl.l_start,
1093 p->u.fcntl.arg.fl.l_len),
1094 p->u.fcntl.arg.fl.l_type);
1098 return p->u.fcntl.ret;
1101 pid_t failtest_getpid(const char *file, unsigned line)
1103 /* You must call failtest_init first! */
1108 void failtest_init(int argc, char *argv[])
1112 orig_pid = getpid();
1114 warnfd = move_fd_to_high(dup(STDERR_FILENO));
1115 for (i = 1; i < argc; i++) {
1116 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1117 failpath = argv[i] + strlen("--failpath=");
1118 } else if (strcmp(argv[i], "--tracepath") == 0) {
1120 failtest_timeout_ms = -1;
1121 } else if (!strncmp(argv[i], "--debugpath=",
1122 strlen("--debugpath="))) {
1123 debugpath = argv[i] + strlen("--debugpath=");
1129 bool failtest_has_failed(void)
1131 return control_fd != -1;
1134 void failtest_exit(int status)
1136 if (failtest_exit_check) {
1137 if (!failtest_exit_check(&history))
1138 child_fail(NULL, 0, "failtest_exit_check failed\n");
1141 failtest_cleanup(false, status);