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 child_fail(out, outlen, "Killed by signal %u: ",
461 /* Child printed failure already, just pass up exit code. */
462 if (type == FAILURE) {
463 fprintf(stderr, "%.*s", (int)outlen, out);
465 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
467 if (WEXITSTATUS(status) != 0)
468 child_fail(out, outlen, "Exited with status %i: ",
469 WEXITSTATUS(status));
472 signal(SIGUSR1, SIG_DFL);
474 restore_files(files);
476 /* We continue onwards without failing. */
481 static void cleanup_calloc(struct calloc_call *call)
486 void *failtest_calloc(size_t nmemb, size_t size,
487 const char *file, unsigned line)
489 struct failtest_call *p;
490 struct calloc_call call;
493 p = add_history(FAILTEST_CALLOC, file, line, &call);
495 if (should_fail(p)) {
496 p->u.calloc.ret = NULL;
499 p->u.calloc.ret = calloc(nmemb, size);
500 set_cleanup(p, cleanup_calloc, struct calloc_call);
503 return p->u.calloc.ret;
506 static void cleanup_malloc(struct malloc_call *call)
511 void *failtest_malloc(size_t size, const char *file, unsigned line)
513 struct failtest_call *p;
514 struct malloc_call call;
517 p = add_history(FAILTEST_MALLOC, file, line, &call);
518 if (should_fail(p)) {
519 p->u.calloc.ret = NULL;
522 p->u.calloc.ret = malloc(size);
523 set_cleanup(p, cleanup_malloc, struct malloc_call);
526 return p->u.calloc.ret;
529 static void cleanup_realloc(struct realloc_call *call)
534 /* Walk back and find out if we got this ptr from a previous routine. */
535 static void fixup_ptr_history(void *ptr, unsigned int last)
539 /* Start at end of history, work back. */
540 for (i = last - 1; i >= 0; i--) {
541 switch (history[i].type) {
542 case FAILTEST_REALLOC:
543 if (history[i].u.realloc.ret == ptr) {
544 history[i].cleanup = NULL;
548 case FAILTEST_MALLOC:
549 if (history[i].u.malloc.ret == ptr) {
550 history[i].cleanup = NULL;
554 case FAILTEST_CALLOC:
555 if (history[i].u.calloc.ret == ptr) {
556 history[i].cleanup = NULL;
566 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
568 struct failtest_call *p;
569 struct realloc_call call;
571 p = add_history(FAILTEST_REALLOC, file, line, &call);
573 /* FIXME: Try one child moving allocation, one not. */
574 if (should_fail(p)) {
575 p->u.realloc.ret = NULL;
578 fixup_ptr_history(ptr, history_num-1);
579 p->u.realloc.ret = realloc(ptr, size);
580 set_cleanup(p, cleanup_realloc, struct realloc_call);
583 return p->u.realloc.ret;
586 void failtest_free(void *ptr)
588 fixup_ptr_history(ptr, history_num);
592 static void cleanup_open(struct open_call *call)
597 int failtest_open(const char *pathname,
598 const char *file, unsigned line, ...)
600 struct failtest_call *p;
601 struct open_call call;
604 call.pathname = strdup(pathname);
606 call.flags = va_arg(ap, int);
607 if (call.flags & O_CREAT) {
608 call.mode = va_arg(ap, mode_t);
611 p = add_history(FAILTEST_OPEN, file, line, &call);
612 /* Avoid memory leak! */
613 if (p == &unrecorded_call)
614 free((char *)call.pathname);
615 p->u.open.ret = open(pathname, call.flags, call.mode);
617 if (!failpath && p->u.open.ret == -1) {
620 } else if (should_fail(p)) {
621 close(p->u.open.ret);
623 /* FIXME: Play with error codes? */
626 set_cleanup(p, cleanup_open, struct open_call);
629 return p->u.open.ret;
632 static void cleanup_pipe(struct pipe_call *call)
634 if (!call->closed[0])
636 if (!call->closed[1])
640 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
642 struct failtest_call *p;
643 struct pipe_call call;
645 p = add_history(FAILTEST_PIPE, file, line, &call);
646 if (should_fail(p)) {
648 /* FIXME: Play with error codes? */
651 p->u.pipe.ret = pipe(p->u.pipe.fds);
652 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
653 set_cleanup(p, cleanup_pipe, struct pipe_call);
655 /* This causes valgrind to notice if they use pipefd[] after failure */
656 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
658 return p->u.pipe.ret;
661 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
662 const char *file, unsigned line)
664 struct failtest_call *p;
665 struct read_call call;
670 p = add_history(FAILTEST_READ, file, line, &call);
672 /* FIXME: Try partial read returns. */
673 if (should_fail(p)) {
677 p->u.read.ret = pread(fd, buf, count, off);
680 return p->u.read.ret;
683 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
684 const char *file, unsigned line)
686 struct failtest_call *p;
687 struct write_call call;
693 p = add_history(FAILTEST_WRITE, file, line, &call);
695 /* If we're a child, we need to make sure we write the same thing
696 * to non-files as the parent does, so tell it. */
697 if (control_fd != -1 && off == (off_t)-1) {
698 enum info_type type = WRITE;
700 write_all(control_fd, &type, sizeof(type));
701 write_all(control_fd, &p->u.write, sizeof(p->u.write));
702 write_all(control_fd, buf, count);
705 /* FIXME: Try partial write returns. */
706 if (should_fail(p)) {
710 /* FIXME: We assume same write order in parent and child */
711 if (off == (off_t)-1 && child_writes_num != 0) {
712 if (child_writes[0].fd != fd)
713 errx(1, "Child wrote to fd %u, not %u?",
714 child_writes[0].fd, fd);
715 if (child_writes[0].off != p->u.write.off)
716 errx(1, "Child wrote to offset %zu, not %zu?",
717 (size_t)child_writes[0].off,
718 (size_t)p->u.write.off);
719 if (child_writes[0].count != count)
720 errx(1, "Child wrote length %zu, not %zu?",
721 child_writes[0].count, count);
722 if (memcmp(child_writes[0].buf, buf, count)) {
724 "Child wrote differently to"
725 " fd %u than we did!\n", fd);
727 free((char *)child_writes[0].buf);
729 memmove(&child_writes[0], &child_writes[1],
730 sizeof(child_writes[0]) * child_writes_num);
732 /* Is this is a socket or pipe, child wrote it
734 if (p->u.write.off == (off_t)-1) {
735 p->u.write.ret = count;
737 return p->u.write.ret;
740 p->u.write.ret = pwrite(fd, buf, count, off);
743 return p->u.write.ret;
746 ssize_t failtest_read(int fd, void *buf, size_t count,
747 const char *file, unsigned line)
749 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
753 ssize_t failtest_write(int fd, const void *buf, size_t count,
754 const char *file, unsigned line)
756 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
760 static struct lock_info *WARN_UNUSED_RESULT
761 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
766 for (i = 0; i < lock_num; i++) {
771 /* Four cases we care about:
785 if (start > l->start && end < l->end) {
786 /* Mid overlap: trim entry, add new one. */
787 off_t new_start, new_end;
791 locks = add_lock(locks,
792 fd, new_start, new_end, l->type);
794 } else if (start <= l->start && end >= l->end) {
795 /* Total overlap: eliminate entry. */
798 } else if (end >= l->start && end < l->end) {
799 /* Start overlap: trim entry. */
801 } else if (start > l->start && start <= l->end) {
802 /* End overlap: trim entry. */
805 /* Nothing left? Remove it. */
806 if (l->end < l->start) {
807 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
812 if (type != F_UNLCK) {
813 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
814 l = &locks[lock_num++];
823 /* We trap this so we can record it: we don't fail it. */
824 int failtest_close(int fd)
831 /* Trace history to find source of fd. */
832 for (i = history_num-1; i >= 0; i--) {
833 switch (history[i].type) {
836 if (history[i].u.pipe.fds[0] == fd) {
837 assert(!history[i].u.pipe.closed[0]);
838 history[i].u.pipe.closed[0] = true;
839 if (history[i].u.pipe.closed[1])
840 history[i].cleanup = NULL;
843 if (history[i].u.pipe.fds[1] == fd) {
844 assert(!history[i].u.pipe.closed[1]);
845 history[i].u.pipe.closed[1] = true;
846 if (history[i].u.pipe.closed[0])
847 history[i].cleanup = NULL;
852 if (history[i].u.open.ret == fd) {
853 assert((void *)history[i].cleanup
854 == (void *)cleanup_open);
855 history[i].cleanup = NULL;
865 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
869 /* Zero length means "to end of file" */
870 static off_t end_of(off_t start, off_t len)
874 return start + len - 1;
877 /* FIXME: This only handles locks, really. */
878 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
880 struct failtest_call *p;
881 struct fcntl_call call;
887 /* Argument extraction. */
892 call.arg.l = va_arg(ap, long);
894 return fcntl(fd, cmd, call.arg.l);
897 return fcntl(fd, cmd);
901 call.arg.fl = *va_arg(ap, struct flock *);
903 return fcntl(fd, cmd, &call.arg.fl);
907 call.arg.fl = *va_arg(ap, struct flock *);
911 /* This means you need to implement it here. */
912 err(1, "failtest: unknown fcntl %u", cmd);
915 p = add_history(FAILTEST_FCNTL, file, line, &call);
918 if (should_fail(p)) {
920 if (p->u.fcntl.cmd == F_SETLK)
925 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
927 if (p->u.fcntl.ret == -1)
930 /* We don't handle anything else yet. */
931 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
932 locks = add_lock(locks,
934 p->u.fcntl.arg.fl.l_start,
935 end_of(p->u.fcntl.arg.fl.l_start,
936 p->u.fcntl.arg.fl.l_len),
937 p->u.fcntl.arg.fl.l_type);
941 return p->u.fcntl.ret;
944 void failtest_init(int argc, char *argv[])
948 for (i = 1; i < argc; i++) {
949 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
950 failpath = argv[i] + strlen("--failpath=");
951 } else if (strcmp(argv[i], "--tracepath") == 0) {
952 tracefd = dup(STDERR_FILENO);
953 failtest_timeout_ms = -1;
954 } else if (!strncmp(argv[i], "--debugpath=",
955 strlen("--debugpath="))) {
956 debugpath = argv[i] + strlen("--debugpath=");
959 gettimeofday(&start, NULL);
962 /* Free up memory, so valgrind doesn't report leaks. */
963 static void free_everything(void)
967 /* We don't do this in cleanup: needed even for failed opens. */
968 for (i = 0; i < history_num; i++) {
969 if (history[i].type == FAILTEST_OPEN)
970 free((char *)history[i].u.open.pathname);
975 void failtest_exit(int status)
979 if (control_fd == -1) {
984 if (failtest_exit_check) {
985 if (!failtest_exit_check(history, history_num))
986 child_fail(NULL, 0, "failtest_exit_check failed\n");
989 /* Cleanup everything, in reverse order. */
990 for (i = history_num - 1; i >= 0; i--)
991 if (history[i].cleanup)
992 history[i].cleanup(&history[i].u);
995 tell_parent(SUCCESS);