10 #include <sys/types.h>
15 #include <ccan/read_write_all/read_write_all.h>
16 #include <ccan/failtest/failtest_proto.h>
17 #include <ccan/failtest/failtest.h>
18 #include <ccan/build_assert/build_assert.h>
20 bool (*failtest_hook)(struct failtest_call *history, unsigned num)
21 = failtest_default_hook;
23 static int tracefd = -1;
25 unsigned int failtest_timeout_ms = 20000;
28 const char *debugpath;
40 /* end is inclusive: you can't have a 0-byte lock. */
45 bool (*failtest_exit_check)(struct failtest_call *history, unsigned num);
47 static struct failtest_call *history = NULL;
48 static unsigned int history_num = 0;
49 static int control_fd = -1;
50 static struct timeval start;
52 static struct write_call *child_writes = NULL;
53 static unsigned int child_writes_num = 0;
55 static pid_t lock_owner;
56 static struct lock_info *locks = NULL;
57 static unsigned int lock_num = 0;
59 static const char info_to_arg[] = "mceoprwf";
61 /* Dummy call used for failtest_undo wrappers. */
62 static struct failtest_call unrecorded_call;
64 static struct failtest_call *add_history_(enum failtest_call_type type,
70 /* NULL file is how we suppress failure. */
72 return &unrecorded_call;
74 history = realloc(history, (history_num + 1) * sizeof(*history));
75 history[history_num].type = type;
76 history[history_num].file = file;
77 history[history_num].line = line;
78 history[history_num].cleanup = NULL;
79 memcpy(&history[history_num].u, elem, elem_size);
80 return &history[history_num++];
83 #define add_history(type, file, line, elem) \
84 add_history_((type), (file), (line), (elem), sizeof(*(elem)))
86 #define set_cleanup(call, clean, type) \
87 (call)->cleanup = (void *)((void)sizeof(clean((type *)NULL)), (clean))
89 bool failtest_default_hook(struct failtest_call *history, unsigned num)
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);
152 static void hand_down(int signal)
157 static void release_locks(void)
159 /* Locks were never acquired/reacquired? */
163 /* We own them? Release them all. */
164 if (lock_owner == getpid()) {
168 fl.l_whence = SEEK_SET;
172 for (i = 0; i < lock_num; i++)
173 fcntl(locks[i].fd, F_SETLK, &fl);
175 /* Our parent must have them; pass request up. */
176 enum info_type type = RELEASE_LOCKS;
177 assert(control_fd != -1);
178 write_all(control_fd, &type, sizeof(type));
183 /* off_t is a signed type. Getting its max is non-trivial. */
184 static off_t off_max(void)
186 BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
187 if (sizeof(off_t) == 4)
188 return (off_t)0x7FFFFFF;
190 return (off_t)0x7FFFFFFFFFFFFFFULL;
193 static void get_locks(void)
198 if (lock_owner == getpid())
201 if (lock_owner != 0) {
202 enum info_type type = RELEASE_LOCKS;
203 assert(control_fd != -1);
204 write_all(control_fd, &type, sizeof(type));
207 fl.l_whence = SEEK_SET;
209 for (i = 0; i < lock_num; i++) {
210 fl.l_type = locks[i].type;
211 fl.l_start = locks[i].start;
212 if (locks[i].end == off_max())
215 fl.l_len = locks[i].end - locks[i].start + 1;
217 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
220 lock_owner = getpid();
223 static void trace_str(const char *str)
227 while ((ret = write(tracefd, str, strlen(str))) <= 0) {
232 err(1, "Writing trace.");
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 read(fd, s->contents, s->len);
255 lseek(fd, s->off, SEEK_SET);
259 /* We have little choice but to save and restore open files: mmap means we
260 * can really intercept changes in the child.
262 * We could do non-mmap'ed files on demand, however. */
263 static struct saved_file *save_files(void)
265 struct saved_file *files = NULL;
268 /* Figure out the set of live fds. */
269 for (i = history_num - 2; i >= 0; i--) {
270 if (history[i].type == FAILTEST_OPEN) {
271 int fd = history[i].u.open.ret;
272 /* Only do successful, writable fds. */
276 /* If it was closed, cleanup == NULL. */
277 if (!history[i].cleanup)
280 if ((history[i].u.open.flags & O_RDWR) == O_RDWR) {
281 files = save_file(files, fd);
282 } else if ((history[i].u.open.flags & O_WRONLY)
284 /* FIXME: Handle O_WRONLY. Open with O_RDWR? */
293 static void restore_files(struct saved_file *s)
296 struct saved_file *next = s->next;
298 lseek(s->fd, 0, SEEK_SET);
299 write(s->fd, s->contents, s->len);
300 ftruncate(s->fd, s->len);
302 lseek(s->fd, s->off, SEEK_SET);
308 static bool should_fail(struct failtest_call *call)
311 int control[2], output[2];
312 enum info_type type = UNEXPECTED;
315 struct saved_file *files;
317 if (call == &unrecorded_call)
321 /* + means continue after end, like normal. */
322 if (*failpath == '+')
325 if (tolower(*failpath) != info_to_arg[call->type])
326 errx(1, "Failpath expected '%c' got '%c'\n",
327 info_to_arg[call->type], *failpath);
328 call->fail = isupper(*(failpath++));
333 /* Attach debugger if they asked for it. */
334 if (debugpath && history_num == strlen(debugpath)) {
337 for (i = 0; i < history_num; i++) {
338 char c = info_to_arg[history[i].type];
341 if (c != debugpath[i])
344 if (i == history_num) {
348 signal(SIGUSR1, SIG_IGN);
349 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
356 if (!failtest_hook(history, history_num)) {
361 files = save_files();
363 /* We're going to fail in the child. */
365 if (pipe(control) != 0 || pipe(output) != 0)
366 err(1, "opening pipe");
368 /* Prevent double-printing (in child and parent) */
372 err(1, "forking failed");
378 gettimeofday(&now, NULL);
379 if (now.tv_usec < start.tv_usec) {
381 now.tv_usec += 1000000;
383 now.tv_usec -= start.tv_usec;
384 now.tv_sec -= start.tv_sec;
385 sprintf(str, "%u (%u.%02u): ", getpid(),
386 (int)now.tv_sec, (int)now.tv_usec / 10000);
388 p = failpath_string();
392 p = strchr(history[history_num-1].file, '/');
396 trace_str(history[history_num-1].file);
397 sprintf(str, ":%u)\n", history[history_num-1].line);
402 dup2(output[1], STDOUT_FILENO);
403 dup2(output[1], STDERR_FILENO);
404 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
406 control_fd = control[1];
410 signal(SIGUSR1, hand_down);
415 /* We grab output so we can display it; we grab writes so we
418 struct pollfd pfd[2];
421 pfd[0].fd = output[0];
422 pfd[0].events = POLLIN|POLLHUP;
423 pfd[1].fd = control[0];
424 pfd[1].events = POLLIN|POLLHUP;
427 ret = poll(pfd, 1, failtest_timeout_ms);
429 ret = poll(pfd, 2, failtest_timeout_ms);
434 if (pfd[0].revents & POLLIN) {
437 out = realloc(out, outlen + 8192);
438 len = read(output[0], out + outlen, 8192);
440 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
441 if (read_all(control[0], &type, sizeof(type))) {
443 if (!read_write_info(control[0]))
445 } else if (type == RELEASE_LOCKS) {
447 /* FIXME: Tell them we're done... */
450 } else if (pfd[0].revents & POLLHUP) {
453 } while (type != FAILURE);
457 waitpid(child, &status, 0);
458 if (!WIFEXITED(status)) {
459 if (WTERMSIG(status) == SIGUSR1)
460 child_fail(out, outlen, "Timed out");
462 child_fail(out, outlen, "Killed by signal %u: ",
465 /* Child printed failure already, just pass up exit code. */
466 if (type == FAILURE) {
467 fprintf(stderr, "%.*s", (int)outlen, out);
469 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
471 if (WEXITSTATUS(status) != 0)
472 child_fail(out, outlen, "Exited with status %i: ",
473 WEXITSTATUS(status));
476 signal(SIGUSR1, SIG_DFL);
478 restore_files(files);
480 /* We continue onwards without failing. */
485 static void cleanup_calloc(struct calloc_call *call)
490 void *failtest_calloc(size_t nmemb, size_t size,
491 const char *file, unsigned line)
493 struct failtest_call *p;
494 struct calloc_call call;
497 p = add_history(FAILTEST_CALLOC, file, line, &call);
499 if (should_fail(p)) {
500 p->u.calloc.ret = NULL;
503 p->u.calloc.ret = calloc(nmemb, size);
504 set_cleanup(p, cleanup_calloc, struct calloc_call);
507 return p->u.calloc.ret;
510 static void cleanup_malloc(struct malloc_call *call)
515 void *failtest_malloc(size_t size, const char *file, unsigned line)
517 struct failtest_call *p;
518 struct malloc_call call;
521 p = add_history(FAILTEST_MALLOC, file, line, &call);
522 if (should_fail(p)) {
523 p->u.calloc.ret = NULL;
526 p->u.calloc.ret = malloc(size);
527 set_cleanup(p, cleanup_malloc, struct malloc_call);
530 return p->u.calloc.ret;
533 static void cleanup_realloc(struct realloc_call *call)
538 /* Walk back and find out if we got this ptr from a previous routine. */
539 static void fixup_ptr_history(void *ptr, unsigned int last)
543 /* Start at end of history, work back. */
544 for (i = last - 1; i >= 0; i--) {
545 switch (history[i].type) {
546 case FAILTEST_REALLOC:
547 if (history[i].u.realloc.ret == ptr) {
548 history[i].cleanup = NULL;
552 case FAILTEST_MALLOC:
553 if (history[i].u.malloc.ret == ptr) {
554 history[i].cleanup = NULL;
558 case FAILTEST_CALLOC:
559 if (history[i].u.calloc.ret == ptr) {
560 history[i].cleanup = NULL;
570 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
572 struct failtest_call *p;
573 struct realloc_call call;
575 p = add_history(FAILTEST_REALLOC, file, line, &call);
577 /* FIXME: Try one child moving allocation, one not. */
578 if (should_fail(p)) {
579 p->u.realloc.ret = NULL;
582 fixup_ptr_history(ptr, history_num-1);
583 p->u.realloc.ret = realloc(ptr, size);
584 set_cleanup(p, cleanup_realloc, struct realloc_call);
587 return p->u.realloc.ret;
590 void failtest_free(void *ptr)
592 fixup_ptr_history(ptr, history_num);
596 static void cleanup_open(struct open_call *call)
601 int failtest_open(const char *pathname,
602 const char *file, unsigned line, ...)
604 struct failtest_call *p;
605 struct open_call call;
608 call.pathname = strdup(pathname);
610 call.flags = va_arg(ap, int);
611 if (call.flags & O_CREAT) {
612 call.mode = va_arg(ap, mode_t);
615 p = add_history(FAILTEST_OPEN, file, line, &call);
616 /* Avoid memory leak! */
617 if (p == &unrecorded_call)
618 free((char *)call.pathname);
619 p->u.open.ret = open(pathname, call.flags, call.mode);
621 if (!failpath && p->u.open.ret == -1) {
624 } else if (should_fail(p)) {
625 close(p->u.open.ret);
627 /* FIXME: Play with error codes? */
630 set_cleanup(p, cleanup_open, struct open_call);
633 return p->u.open.ret;
636 static void cleanup_pipe(struct pipe_call *call)
638 if (!call->closed[0])
640 if (!call->closed[1])
644 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
646 struct failtest_call *p;
647 struct pipe_call call;
649 p = add_history(FAILTEST_PIPE, file, line, &call);
650 if (should_fail(p)) {
652 /* FIXME: Play with error codes? */
655 p->u.pipe.ret = pipe(p->u.pipe.fds);
656 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
657 set_cleanup(p, cleanup_pipe, struct pipe_call);
659 /* This causes valgrind to notice if they use pipefd[] after failure */
660 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
662 return p->u.pipe.ret;
665 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
666 const char *file, unsigned line)
668 struct failtest_call *p;
669 struct read_call call;
674 p = add_history(FAILTEST_READ, file, line, &call);
676 /* FIXME: Try partial read returns. */
677 if (should_fail(p)) {
681 p->u.read.ret = pread(fd, buf, count, off);
684 return p->u.read.ret;
687 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
688 const char *file, unsigned line)
690 struct failtest_call *p;
691 struct write_call call;
697 p = add_history(FAILTEST_WRITE, file, line, &call);
699 /* If we're a child, we need to make sure we write the same thing
700 * to non-files as the parent does, so tell it. */
701 if (control_fd != -1 && off == (off_t)-1) {
702 enum info_type type = WRITE;
704 write_all(control_fd, &type, sizeof(type));
705 write_all(control_fd, &p->u.write, sizeof(p->u.write));
706 write_all(control_fd, buf, count);
709 /* FIXME: Try partial write returns. */
710 if (should_fail(p)) {
714 /* FIXME: We assume same write order in parent and child */
715 if (off == (off_t)-1 && child_writes_num != 0) {
716 if (child_writes[0].fd != fd)
717 errx(1, "Child wrote to fd %u, not %u?",
718 child_writes[0].fd, fd);
719 if (child_writes[0].off != p->u.write.off)
720 errx(1, "Child wrote to offset %zu, not %zu?",
721 (size_t)child_writes[0].off,
722 (size_t)p->u.write.off);
723 if (child_writes[0].count != count)
724 errx(1, "Child wrote length %zu, not %zu?",
725 child_writes[0].count, count);
726 if (memcmp(child_writes[0].buf, buf, count)) {
728 "Child wrote differently to"
729 " fd %u than we did!\n", fd);
731 free((char *)child_writes[0].buf);
733 memmove(&child_writes[0], &child_writes[1],
734 sizeof(child_writes[0]) * child_writes_num);
736 /* Is this is a socket or pipe, child wrote it
738 if (p->u.write.off == (off_t)-1) {
739 p->u.write.ret = count;
741 return p->u.write.ret;
744 p->u.write.ret = pwrite(fd, buf, count, off);
747 return p->u.write.ret;
750 ssize_t failtest_read(int fd, void *buf, size_t count,
751 const char *file, unsigned line)
753 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
757 ssize_t failtest_write(int fd, const void *buf, size_t count,
758 const char *file, unsigned line)
760 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
764 static struct lock_info *WARN_UNUSED_RESULT
765 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
770 for (i = 0; i < lock_num; i++) {
775 /* Four cases we care about:
789 if (start > l->start && end < l->end) {
790 /* Mid overlap: trim entry, add new one. */
791 off_t new_start, new_end;
795 locks = add_lock(locks,
796 fd, new_start, new_end, l->type);
798 } else if (start <= l->start && end >= l->end) {
799 /* Total overlap: eliminate entry. */
802 } else if (end >= l->start && end < l->end) {
803 /* Start overlap: trim entry. */
805 } else if (start > l->start && start <= l->end) {
806 /* End overlap: trim entry. */
809 /* Nothing left? Remove it. */
810 if (l->end < l->start) {
811 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
816 if (type != F_UNLCK) {
817 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
818 l = &locks[lock_num++];
827 /* We trap this so we can record it: we don't fail it. */
828 int failtest_close(int fd)
835 /* Trace history to find source of fd. */
836 for (i = history_num-1; i >= 0; i--) {
837 switch (history[i].type) {
840 if (history[i].u.pipe.fds[0] == fd) {
841 assert(!history[i].u.pipe.closed[0]);
842 history[i].u.pipe.closed[0] = true;
843 if (history[i].u.pipe.closed[1])
844 history[i].cleanup = NULL;
847 if (history[i].u.pipe.fds[1] == fd) {
848 assert(!history[i].u.pipe.closed[1]);
849 history[i].u.pipe.closed[1] = true;
850 if (history[i].u.pipe.closed[0])
851 history[i].cleanup = NULL;
856 if (history[i].u.open.ret == fd) {
857 assert((void *)history[i].cleanup
858 == (void *)cleanup_open);
859 history[i].cleanup = NULL;
869 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
873 /* Zero length means "to end of file" */
874 static off_t end_of(off_t start, off_t len)
878 return start + len - 1;
881 /* FIXME: This only handles locks, really. */
882 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
884 struct failtest_call *p;
885 struct fcntl_call call;
891 /* Argument extraction. */
896 call.arg.l = va_arg(ap, long);
898 return fcntl(fd, cmd, call.arg.l);
901 return fcntl(fd, cmd);
905 call.arg.fl = *va_arg(ap, struct flock *);
907 return fcntl(fd, cmd, &call.arg.fl);
911 call.arg.fl = *va_arg(ap, struct flock *);
915 /* This means you need to implement it here. */
916 err(1, "failtest: unknown fcntl %u", cmd);
919 p = add_history(FAILTEST_FCNTL, file, line, &call);
922 if (should_fail(p)) {
924 if (p->u.fcntl.cmd == F_SETLK)
929 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
931 if (p->u.fcntl.ret == -1)
934 /* We don't handle anything else yet. */
935 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
936 locks = add_lock(locks,
938 p->u.fcntl.arg.fl.l_start,
939 end_of(p->u.fcntl.arg.fl.l_start,
940 p->u.fcntl.arg.fl.l_len),
941 p->u.fcntl.arg.fl.l_type);
945 return p->u.fcntl.ret;
948 void failtest_init(int argc, char *argv[])
952 for (i = 1; i < argc; i++) {
953 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
954 failpath = argv[i] + strlen("--failpath=");
955 } else if (strcmp(argv[i], "--tracepath") == 0) {
956 tracefd = dup(STDERR_FILENO);
957 failtest_timeout_ms = -1;
958 } else if (!strncmp(argv[i], "--debugpath=",
959 strlen("--debugpath="))) {
960 debugpath = argv[i] + strlen("--debugpath=");
963 gettimeofday(&start, NULL);
966 /* Free up memory, so valgrind doesn't report leaks. */
967 static void free_everything(void)
971 /* We don't do this in cleanup: needed even for failed opens. */
972 for (i = 0; i < history_num; i++) {
973 if (history[i].type == FAILTEST_OPEN)
974 free((char *)history[i].u.open.pathname);
979 void failtest_exit(int status)
983 if (failtest_exit_check) {
984 if (!failtest_exit_check(history, history_num))
985 child_fail(NULL, 0, "failtest_exit_check failed\n");
988 if (control_fd == -1) {
993 /* Cleanup everything, in reverse order. */
994 for (i = history_num - 1; i >= 0; i--)
995 if (history[i].cleanup)
996 history[i].cleanup(&history[i].u);
999 tell_parent(SUCCESS);