11 #include <sys/types.h>
16 #include <ccan/read_write_all/read_write_all.h>
17 #include <ccan/failtest/failtest_proto.h>
18 #include <ccan/failtest/failtest.h>
19 #include <ccan/build_assert/build_assert.h>
21 enum failtest_result (*failtest_hook)(struct failtest_call *, unsigned);
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;
51 static unsigned int probe_count = 0;
53 static struct write_call *child_writes = NULL;
54 static unsigned int child_writes_num = 0;
56 static pid_t lock_owner;
57 static struct lock_info *locks = NULL;
58 static unsigned int lock_num = 0;
60 static const char info_to_arg[] = "mceoxprwf";
62 /* Dummy call used for failtest_undo wrappers. */
63 static struct failtest_call unrecorded_call;
65 static struct failtest_call *add_history_(enum failtest_call_type type,
71 /* NULL file is how we suppress failure. */
73 return &unrecorded_call;
75 history = realloc(history, (history_num + 1) * sizeof(*history));
76 history[history_num].type = type;
77 history[history_num].file = file;
78 history[history_num].line = line;
79 history[history_num].cleanup = NULL;
80 memcpy(&history[history_num].u, elem, elem_size);
81 return &history[history_num++];
84 #define add_history(type, file, line, elem) \
85 add_history_((type), (file), (line), (elem), sizeof(*(elem)))
87 /* We do a fake call inside a sizeof(), to check types. */
88 #define set_cleanup(call, clean, type) \
89 (call)->cleanup = (void *)((void)sizeof(clean((type *)NULL),1), (clean))
91 static bool read_write_info(int fd)
96 /* We don't need all of this, but it's simple. */
97 child_writes = realloc(child_writes,
98 (child_writes_num+1) * sizeof(child_writes[0]));
99 w = &child_writes[child_writes_num];
100 if (!read_all(fd, w, sizeof(*w)))
103 w->buf = buf = malloc(w->count);
104 if (!read_all(fd, buf, w->count))
111 static char *failpath_string(void)
114 char *ret = malloc(history_num + 1);
116 for (i = 0; i < history_num; i++) {
117 ret[i] = info_to_arg[history[i].type];
119 ret[i] = toupper(ret[i]);
125 static void tell_parent(enum info_type type)
127 if (control_fd != -1)
128 write_all(control_fd, &type, sizeof(type));
131 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
134 char *path = failpath_string();
137 vfprintf(stderr, fmt, ap);
140 fprintf(stderr, "%.*s", (int)outlen, out);
141 printf("To reproduce: --failpath=%s\n", path);
143 tell_parent(FAILURE);
147 static void trace(const char *fmt, ...)
155 vdprintf(tracefd, fmt, ap);
161 static void hand_down(int signum)
166 static void release_locks(void)
168 /* Locks were never acquired/reacquired? */
172 /* We own them? Release them all. */
173 if (lock_owner == getpid()) {
177 fl.l_whence = SEEK_SET;
181 for (i = 0; i < lock_num; i++)
182 fcntl(locks[i].fd, F_SETLK, &fl);
184 /* Our parent must have them; pass request up. */
185 enum info_type type = RELEASE_LOCKS;
186 assert(control_fd != -1);
187 write_all(control_fd, &type, sizeof(type));
192 /* off_t is a signed type. Getting its max is non-trivial. */
193 static off_t off_max(void)
195 BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
196 if (sizeof(off_t) == 4)
197 return (off_t)0x7FFFFFF;
199 return (off_t)0x7FFFFFFFFFFFFFFULL;
202 static void get_locks(void)
207 if (lock_owner == getpid())
210 if (lock_owner != 0) {
211 enum info_type type = RELEASE_LOCKS;
212 assert(control_fd != -1);
213 write_all(control_fd, &type, sizeof(type));
216 fl.l_whence = SEEK_SET;
218 for (i = 0; i < lock_num; i++) {
219 fl.l_type = locks[i].type;
220 fl.l_start = locks[i].start;
221 if (locks[i].end == off_max())
224 fl.l_len = locks[i].end - locks[i].start + 1;
226 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
229 lock_owner = getpid();
233 struct saved_file *next;
239 static struct saved_file *save_file(struct saved_file *next, int fd)
241 struct saved_file *s = malloc(sizeof(*s));
245 s->off = lseek(fd, 0, SEEK_CUR);
246 /* Special file? Erk... */
247 assert(s->off != -1);
248 s->len = lseek(fd, 0, SEEK_END);
249 lseek(fd, 0, SEEK_SET);
250 s->contents = malloc(s->len);
251 if (read(fd, s->contents, s->len) != s->len)
252 err(1, "Failed to save %zu bytes", (size_t)s->len);
253 lseek(fd, s->off, SEEK_SET);
257 /* We have little choice but to save and restore open files: mmap means we
258 * can really intercept changes in the child.
260 * We could do non-mmap'ed files on demand, however. */
261 static struct saved_file *save_files(void)
263 struct saved_file *files = NULL;
266 /* Figure out the set of live fds. */
267 for (i = history_num - 2; i >= 0; i--) {
268 if (history[i].type == FAILTEST_OPEN) {
269 int fd = history[i].u.open.ret;
270 /* Only do successful, writable fds. */
274 /* If it was closed, cleanup == NULL. */
275 if (!history[i].cleanup)
278 if ((history[i].u.open.flags & O_RDWR) == O_RDWR) {
279 files = save_file(files, fd);
280 } else if ((history[i].u.open.flags & O_WRONLY)
282 /* FIXME: Handle O_WRONLY. Open with O_RDWR? */
291 static void restore_files(struct saved_file *s)
294 struct saved_file *next = s->next;
296 lseek(s->fd, 0, SEEK_SET);
297 if (write(s->fd, s->contents, s->len) != s->len)
298 err(1, "Failed to restore %zu bytes", (size_t)s->len);
299 if (ftruncate(s->fd, s->len) != 0)
300 err(1, "Failed to trim file to length %zu",
303 lseek(s->fd, s->off, SEEK_SET);
309 /* Free up memory, so valgrind doesn't report leaks. */
310 static void free_everything(void)
314 /* We don't do this in cleanup: needed even for failed opens. */
315 for (i = 0; i < history_num; i++) {
316 if (history[i].type == FAILTEST_OPEN)
317 free((char *)history[i].u.open.pathname);
322 static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
326 /* For children, we don't care if they "failed" the testing. */
327 if (control_fd != -1)
333 /* Cleanup everything, in reverse order. */
334 for (i = history_num - 1; i >= 0; i--) {
335 if (!history[i].cleanup)
337 if (!forced_cleanup) {
338 printf("Leak at %s:%u: --failpath=%s\n",
339 history[i].file, history[i].line,
343 history[i].cleanup(&history[i].u);
347 tell_parent(SUCCESS);
351 static bool should_fail(struct failtest_call *call)
354 int control[2], output[2];
355 enum info_type type = UNEXPECTED;
358 struct saved_file *files;
360 /* Are we probing? */
361 if (probe_count && --probe_count == 0)
362 failtest_cleanup(true, 0);
364 if (call == &unrecorded_call)
368 /* + means continue after end, like normal. */
369 if (*failpath == '+')
371 else if (*failpath == '\0') {
372 /* Continue, but don't inject errors. */
373 return call->fail = false;
375 if (tolower((unsigned char)*failpath)
376 != info_to_arg[call->type])
377 errx(1, "Failpath expected '%c' got '%c'\n",
378 info_to_arg[call->type], *failpath);
379 call->fail = isupper((unsigned char)*(failpath++));
384 /* Attach debugger if they asked for it. */
385 if (debugpath && history_num == strlen(debugpath)) {
388 for (i = 0; i < history_num; i++) {
389 unsigned char c = info_to_arg[history[i].type];
392 if (c != debugpath[i])
395 if (i == history_num) {
399 signal(SIGUSR1, SIG_IGN);
400 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
402 if (system(str) == 0)
408 switch (failtest_hook(history, history_num)) {
415 /* Already down probe path? Stop now. */
417 failtest_cleanup(true, 0);
418 /* FIXME: We should run *parent* and run probe until
419 * calls match up again. */
427 files = save_files();
429 /* We're going to fail in the child. */
431 if (pipe(control) != 0 || pipe(output) != 0)
432 err(1, "opening pipe");
434 /* Prevent double-printing (in child and parent) */
438 err(1, "forking failed");
444 gettimeofday(&now, NULL);
445 if (now.tv_usec < start.tv_usec) {
447 now.tv_usec += 1000000;
449 now.tv_usec -= start.tv_usec;
450 now.tv_sec -= start.tv_sec;
451 p = failpath_string();
452 trace("%u->%u (%u.%02u): %s (", getppid(), getpid(),
453 (int)now.tv_sec, (int)now.tv_usec / 10000, p);
455 p = strrchr(history[history_num-1].file, '/');
459 trace("%s", history[history_num-1].file);
460 trace(":%u)\n", history[history_num-1].line);
464 dup2(output[1], STDOUT_FILENO);
465 dup2(output[1], STDERR_FILENO);
466 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
468 control_fd = control[1];
472 signal(SIGUSR1, hand_down);
477 /* We grab output so we can display it; we grab writes so we
480 struct pollfd pfd[2];
483 pfd[0].fd = output[0];
484 pfd[0].events = POLLIN|POLLHUP;
485 pfd[1].fd = control[0];
486 pfd[1].events = POLLIN|POLLHUP;
489 ret = poll(pfd, 1, failtest_timeout_ms);
491 ret = poll(pfd, 2, failtest_timeout_ms);
498 err(1, "Poll returned %i", ret);
501 if (pfd[0].revents & POLLIN) {
504 out = realloc(out, outlen + 8192);
505 len = read(output[0], out + outlen, 8192);
507 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
508 if (read_all(control[0], &type, sizeof(type))) {
510 if (!read_write_info(control[0]))
512 } else if (type == RELEASE_LOCKS) {
514 /* FIXME: Tell them we're done... */
517 } else if (pfd[0].revents & POLLHUP) {
520 } while (type != FAILURE);
524 waitpid(child, &status, 0);
525 if (!WIFEXITED(status)) {
526 if (WTERMSIG(status) == SIGUSR1)
527 child_fail(out, outlen, "Timed out");
529 child_fail(out, outlen, "Killed by signal %u: ",
532 /* Child printed failure already, just pass up exit code. */
533 if (type == FAILURE) {
534 fprintf(stderr, "%.*s", (int)outlen, out);
536 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
538 if (WEXITSTATUS(status) != 0)
539 child_fail(out, outlen, "Exited with status %i: ",
540 WEXITSTATUS(status));
543 signal(SIGUSR1, SIG_DFL);
545 restore_files(files);
547 /* We continue onwards without failing. */
552 static void cleanup_calloc(struct calloc_call *call)
557 void *failtest_calloc(size_t nmemb, size_t size,
558 const char *file, unsigned line)
560 struct failtest_call *p;
561 struct calloc_call call;
564 p = add_history(FAILTEST_CALLOC, file, line, &call);
566 if (should_fail(p)) {
567 p->u.calloc.ret = NULL;
570 p->u.calloc.ret = calloc(nmemb, size);
571 set_cleanup(p, cleanup_calloc, struct calloc_call);
574 return p->u.calloc.ret;
577 static void cleanup_malloc(struct malloc_call *call)
582 void *failtest_malloc(size_t size, const char *file, unsigned line)
584 struct failtest_call *p;
585 struct malloc_call call;
588 p = add_history(FAILTEST_MALLOC, file, line, &call);
589 if (should_fail(p)) {
590 p->u.calloc.ret = NULL;
593 p->u.calloc.ret = malloc(size);
594 set_cleanup(p, cleanup_malloc, struct malloc_call);
597 return p->u.calloc.ret;
600 static void cleanup_realloc(struct realloc_call *call)
605 /* Walk back and find out if we got this ptr from a previous routine. */
606 static void fixup_ptr_history(void *ptr, unsigned int last)
610 /* Start at end of history, work back. */
611 for (i = last - 1; i >= 0; i--) {
612 switch (history[i].type) {
613 case FAILTEST_REALLOC:
614 if (history[i].u.realloc.ret == ptr) {
615 history[i].cleanup = NULL;
619 case FAILTEST_MALLOC:
620 if (history[i].u.malloc.ret == ptr) {
621 history[i].cleanup = NULL;
625 case FAILTEST_CALLOC:
626 if (history[i].u.calloc.ret == ptr) {
627 history[i].cleanup = NULL;
637 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
639 struct failtest_call *p;
640 struct realloc_call call;
642 p = add_history(FAILTEST_REALLOC, file, line, &call);
644 /* FIXME: Try one child moving allocation, one not. */
645 if (should_fail(p)) {
646 p->u.realloc.ret = NULL;
649 fixup_ptr_history(ptr, history_num-1);
650 p->u.realloc.ret = realloc(ptr, size);
651 set_cleanup(p, cleanup_realloc, struct realloc_call);
654 return p->u.realloc.ret;
657 void failtest_free(void *ptr)
659 fixup_ptr_history(ptr, history_num);
663 static void cleanup_open(struct open_call *call)
668 int failtest_open(const char *pathname,
669 const char *file, unsigned line, ...)
671 struct failtest_call *p;
672 struct open_call call;
675 call.pathname = strdup(pathname);
677 call.flags = va_arg(ap, int);
678 if (call.flags & O_CREAT) {
679 call.mode = va_arg(ap, mode_t);
682 p = add_history(FAILTEST_OPEN, file, line, &call);
683 /* Avoid memory leak! */
684 if (p == &unrecorded_call)
685 free((char *)call.pathname);
686 p->u.open.ret = open(pathname, call.flags, call.mode);
688 if (!failpath && p->u.open.ret == -1) {
691 } else if (should_fail(p)) {
692 close(p->u.open.ret);
694 /* FIXME: Play with error codes? */
697 set_cleanup(p, cleanup_open, struct open_call);
700 return p->u.open.ret;
703 static void cleanup_pipe(struct pipe_call *call)
705 if (!call->closed[0])
707 if (!call->closed[1])
711 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
713 struct failtest_call *p;
714 struct pipe_call call;
716 p = add_history(FAILTEST_PIPE, file, line, &call);
717 if (should_fail(p)) {
719 /* FIXME: Play with error codes? */
722 p->u.pipe.ret = pipe(p->u.pipe.fds);
723 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
724 set_cleanup(p, cleanup_pipe, struct pipe_call);
726 /* This causes valgrind to notice if they use pipefd[] after failure */
727 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
729 return p->u.pipe.ret;
732 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
733 const char *file, unsigned line)
735 struct failtest_call *p;
736 struct read_call call;
741 p = add_history(FAILTEST_READ, file, line, &call);
743 /* FIXME: Try partial read returns. */
744 if (should_fail(p)) {
748 p->u.read.ret = pread(fd, buf, count, off);
751 return p->u.read.ret;
754 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
755 const char *file, unsigned line)
757 struct failtest_call *p;
758 struct write_call call;
764 p = add_history(FAILTEST_WRITE, file, line, &call);
766 /* If we're a child, we need to make sure we write the same thing
767 * to non-files as the parent does, so tell it. */
768 if (control_fd != -1 && off == (off_t)-1) {
769 enum info_type type = WRITE;
771 write_all(control_fd, &type, sizeof(type));
772 write_all(control_fd, &p->u.write, sizeof(p->u.write));
773 write_all(control_fd, buf, count);
776 /* FIXME: Try partial write returns. */
777 if (should_fail(p)) {
781 /* FIXME: We assume same write order in parent and child */
782 if (off == (off_t)-1 && child_writes_num != 0) {
783 if (child_writes[0].fd != fd)
784 errx(1, "Child wrote to fd %u, not %u?",
785 child_writes[0].fd, fd);
786 if (child_writes[0].off != p->u.write.off)
787 errx(1, "Child wrote to offset %zu, not %zu?",
788 (size_t)child_writes[0].off,
789 (size_t)p->u.write.off);
790 if (child_writes[0].count != count)
791 errx(1, "Child wrote length %zu, not %zu?",
792 child_writes[0].count, count);
793 if (memcmp(child_writes[0].buf, buf, count)) {
795 "Child wrote differently to"
796 " fd %u than we did!\n", fd);
798 free((char *)child_writes[0].buf);
800 memmove(&child_writes[0], &child_writes[1],
801 sizeof(child_writes[0]) * child_writes_num);
803 /* Is this is a socket or pipe, child wrote it
805 if (p->u.write.off == (off_t)-1) {
806 p->u.write.ret = count;
808 return p->u.write.ret;
811 p->u.write.ret = pwrite(fd, buf, count, off);
814 return p->u.write.ret;
817 ssize_t failtest_read(int fd, void *buf, size_t count,
818 const char *file, unsigned line)
820 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
824 ssize_t failtest_write(int fd, const void *buf, size_t count,
825 const char *file, unsigned line)
827 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
831 static struct lock_info *WARN_UNUSED_RESULT
832 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
837 for (i = 0; i < lock_num; i++) {
842 /* Four cases we care about:
856 if (start > l->start && end < l->end) {
857 /* Mid overlap: trim entry, add new one. */
858 off_t new_start, new_end;
862 locks = add_lock(locks,
863 fd, new_start, new_end, l->type);
865 } else if (start <= l->start && end >= l->end) {
866 /* Total overlap: eliminate entry. */
869 } else if (end >= l->start && end < l->end) {
870 /* Start overlap: trim entry. */
872 } else if (start > l->start && start <= l->end) {
873 /* End overlap: trim entry. */
876 /* Nothing left? Remove it. */
877 if (l->end < l->start) {
878 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
883 if (type != F_UNLCK) {
884 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
885 l = &locks[lock_num++];
894 /* We trap this so we can record it: we don't fail it. */
895 int failtest_close(int fd, const char *file, unsigned line)
898 struct close_call call;
899 struct failtest_call *p;
902 p = add_history(FAILTEST_CLOSE, file, line, &call);
905 /* Consume close from failpath. */
913 /* Trace history to find source of fd. */
914 for (i = history_num-1; i >= 0; i--) {
915 switch (history[i].type) {
918 if (history[i].u.pipe.fds[0] == fd) {
919 assert(!history[i].u.pipe.closed[0]);
920 history[i].u.pipe.closed[0] = true;
921 if (history[i].u.pipe.closed[1])
922 history[i].cleanup = NULL;
925 if (history[i].u.pipe.fds[1] == fd) {
926 assert(!history[i].u.pipe.closed[1]);
927 history[i].u.pipe.closed[1] = true;
928 if (history[i].u.pipe.closed[0])
929 history[i].cleanup = NULL;
934 if (history[i].u.open.ret == fd) {
935 assert((void *)history[i].cleanup
936 == (void *)cleanup_open);
937 history[i].cleanup = NULL;
947 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
951 /* Zero length means "to end of file" */
952 static off_t end_of(off_t start, off_t len)
956 return start + len - 1;
959 /* FIXME: This only handles locks, really. */
960 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
962 struct failtest_call *p;
963 struct fcntl_call call;
969 /* Argument extraction. */
974 call.arg.l = va_arg(ap, long);
976 return fcntl(fd, cmd, call.arg.l);
979 return fcntl(fd, cmd);
983 call.arg.fl = *va_arg(ap, struct flock *);
985 return fcntl(fd, cmd, &call.arg.fl);
989 call.arg.fl = *va_arg(ap, struct flock *);
993 /* This means you need to implement it here. */
994 err(1, "failtest: unknown fcntl %u", cmd);
997 p = add_history(FAILTEST_FCNTL, file, line, &call);
999 if (should_fail(p)) {
1000 p->u.fcntl.ret = -1;
1001 if (p->u.fcntl.cmd == F_SETLK)
1007 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
1008 &p->u.fcntl.arg.fl);
1009 if (p->u.fcntl.ret == -1)
1012 /* We don't handle anything else yet. */
1013 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1014 locks = add_lock(locks,
1016 p->u.fcntl.arg.fl.l_start,
1017 end_of(p->u.fcntl.arg.fl.l_start,
1018 p->u.fcntl.arg.fl.l_len),
1019 p->u.fcntl.arg.fl.l_type);
1023 return p->u.fcntl.ret;
1026 void failtest_init(int argc, char *argv[])
1030 for (i = 1; i < argc; i++) {
1031 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1032 failpath = argv[i] + strlen("--failpath=");
1033 } else if (strcmp(argv[i], "--tracepath") == 0) {
1034 tracefd = dup(STDERR_FILENO);
1035 failtest_timeout_ms = -1;
1036 } else if (!strncmp(argv[i], "--debugpath=",
1037 strlen("--debugpath="))) {
1038 debugpath = argv[i] + strlen("--debugpath=");
1041 gettimeofday(&start, NULL);
1044 void failtest_exit(int status)
1046 if (failtest_exit_check) {
1047 if (!failtest_exit_check(history, history_num))
1048 child_fail(NULL, 0, "failtest_exit_check failed\n");
1051 failtest_cleanup(false, status);