11 #include <sys/types.h>
17 #include <ccan/read_write_all/read_write_all.h>
18 #include <ccan/failtest/failtest_proto.h>
19 #include <ccan/failtest/failtest.h>
20 #include <ccan/build_assert/build_assert.h>
22 enum failtest_result (*failtest_hook)(struct failtest_call *, unsigned);
24 static int tracefd = -1;
26 unsigned int failtest_timeout_ms = 20000;
29 const char *debugpath;
41 /* end is inclusive: you can't have a 0-byte lock. */
46 bool (*failtest_exit_check)(struct failtest_call *history, unsigned num);
48 static struct failtest_call *history = NULL;
49 static unsigned int history_num = 0;
50 static int control_fd = -1;
51 static struct timeval start;
52 static unsigned int probe_count = 0;
54 static struct write_call *child_writes = NULL;
55 static unsigned int child_writes_num = 0;
57 static pid_t lock_owner;
58 static struct lock_info *locks = NULL;
59 static unsigned int lock_num = 0;
61 static const char info_to_arg[] = "mceoxprwf";
63 /* Dummy call used for failtest_undo wrappers. */
64 static struct failtest_call unrecorded_call;
66 static struct failtest_call *add_history_(enum failtest_call_type type,
72 /* NULL file is how we suppress failure. */
74 return &unrecorded_call;
76 history = realloc(history, (history_num + 1) * sizeof(*history));
77 history[history_num].type = type;
78 history[history_num].file = file;
79 history[history_num].line = line;
80 history[history_num].cleanup = NULL;
81 memcpy(&history[history_num].u, elem, elem_size);
82 return &history[history_num++];
85 #define add_history(type, file, line, elem) \
86 add_history_((type), (file), (line), (elem), sizeof(*(elem)))
88 /* We do a fake call inside a sizeof(), to check types. */
89 #define set_cleanup(call, clean, type) \
90 (call)->cleanup = (void *)((void)sizeof(clean((type *)NULL),1), (clean))
92 static bool read_write_info(int fd)
97 /* We don't need all of this, but it's simple. */
98 child_writes = realloc(child_writes,
99 (child_writes_num+1) * sizeof(child_writes[0]));
100 w = &child_writes[child_writes_num];
101 if (!read_all(fd, w, sizeof(*w)))
104 w->buf = buf = malloc(w->count);
105 if (!read_all(fd, buf, w->count))
112 static char *failpath_string(void)
115 char *ret = malloc(history_num + 1);
117 for (i = 0; i < history_num; i++) {
118 ret[i] = info_to_arg[history[i].type];
120 ret[i] = toupper(ret[i]);
126 static void tell_parent(enum info_type type)
128 if (control_fd != -1)
129 write_all(control_fd, &type, sizeof(type));
132 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
135 char *path = failpath_string();
138 vfprintf(stderr, fmt, ap);
141 fprintf(stderr, "%.*s", (int)outlen, out);
142 printf("To reproduce: --failpath=%s\n", path);
144 tell_parent(FAILURE);
148 static void trace(const char *fmt, ...)
156 vdprintf(tracefd, fmt, ap);
162 static void hand_down(int signum)
167 static void release_locks(void)
169 /* Locks were never acquired/reacquired? */
173 /* We own them? Release them all. */
174 if (lock_owner == getpid()) {
178 fl.l_whence = SEEK_SET;
182 for (i = 0; i < lock_num; i++)
183 fcntl(locks[i].fd, F_SETLK, &fl);
185 /* Our parent must have them; pass request up. */
186 enum info_type type = RELEASE_LOCKS;
187 assert(control_fd != -1);
188 write_all(control_fd, &type, sizeof(type));
193 /* off_t is a signed type. Getting its max is non-trivial. */
194 static off_t off_max(void)
196 BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
197 if (sizeof(off_t) == 4)
198 return (off_t)0x7FFFFFF;
200 return (off_t)0x7FFFFFFFFFFFFFFULL;
203 static void get_locks(void)
208 if (lock_owner == getpid())
211 if (lock_owner != 0) {
212 enum info_type type = RELEASE_LOCKS;
213 assert(control_fd != -1);
214 write_all(control_fd, &type, sizeof(type));
217 fl.l_whence = SEEK_SET;
219 for (i = 0; i < lock_num; i++) {
220 fl.l_type = locks[i].type;
221 fl.l_start = locks[i].start;
222 if (locks[i].end == off_max())
225 fl.l_len = locks[i].end - locks[i].start + 1;
227 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
230 lock_owner = getpid();
234 struct saved_file *next;
240 static struct saved_file *save_file(struct saved_file *next, int fd)
242 struct saved_file *s = malloc(sizeof(*s));
246 s->off = lseek(fd, 0, SEEK_CUR);
247 /* Special file? Erk... */
248 assert(s->off != -1);
249 s->len = lseek(fd, 0, SEEK_END);
250 lseek(fd, 0, SEEK_SET);
251 s->contents = malloc(s->len);
252 if (read(fd, s->contents, s->len) != s->len)
253 err(1, "Failed to save %zu bytes", (size_t)s->len);
254 lseek(fd, s->off, SEEK_SET);
258 /* We have little choice but to save and restore open files: mmap means we
259 * can really intercept changes in the child.
261 * We could do non-mmap'ed files on demand, however. */
262 static struct saved_file *save_files(void)
264 struct saved_file *files = NULL;
267 /* Figure out the set of live fds. */
268 for (i = history_num - 2; i >= 0; i--) {
269 if (history[i].type == FAILTEST_OPEN) {
270 int fd = history[i].u.open.ret;
271 /* Only do successful, writable fds. */
275 /* If it was closed, cleanup == NULL. */
276 if (!history[i].cleanup)
279 if ((history[i].u.open.flags & O_RDWR) == O_RDWR) {
280 files = save_file(files, fd);
281 } else if ((history[i].u.open.flags & O_WRONLY)
283 /* FIXME: Handle O_WRONLY. Open with O_RDWR? */
292 static void restore_files(struct saved_file *s)
295 struct saved_file *next = s->next;
297 lseek(s->fd, 0, SEEK_SET);
298 if (write(s->fd, s->contents, s->len) != s->len)
299 err(1, "Failed to restore %zu bytes", (size_t)s->len);
300 if (ftruncate(s->fd, s->len) != 0)
301 err(1, "Failed to trim file to length %zu",
304 lseek(s->fd, s->off, SEEK_SET);
310 /* Free up memory, so valgrind doesn't report leaks. */
311 static void free_everything(void)
315 /* We don't do this in cleanup: needed even for failed opens. */
316 for (i = 0; i < history_num; i++) {
317 if (history[i].type == FAILTEST_OPEN)
318 free((char *)history[i].u.open.pathname);
323 static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
327 /* For children, we don't care if they "failed" the testing. */
328 if (control_fd != -1)
334 /* Cleanup everything, in reverse order. */
335 for (i = history_num - 1; i >= 0; i--) {
336 if (!history[i].cleanup)
338 if (!forced_cleanup) {
339 printf("Leak at %s:%u: --failpath=%s\n",
340 history[i].file, history[i].line,
344 history[i].cleanup(&history[i].u);
348 tell_parent(SUCCESS);
352 static bool should_fail(struct failtest_call *call)
355 int control[2], output[2];
356 enum info_type type = UNEXPECTED;
359 struct saved_file *files;
361 /* Are we probing? */
362 if (probe_count && --probe_count == 0)
363 failtest_cleanup(true, 0);
365 if (call == &unrecorded_call)
369 /* + means continue after end, like normal. */
370 if (*failpath == '+')
372 else if (*failpath == '\0') {
373 /* Continue, but don't inject errors. */
374 return call->fail = false;
376 if (tolower((unsigned char)*failpath)
377 != info_to_arg[call->type])
378 errx(1, "Failpath expected '%c' got '%c'\n",
379 info_to_arg[call->type], *failpath);
380 call->fail = isupper((unsigned char)*(failpath++));
385 /* Attach debugger if they asked for it. */
386 if (debugpath && history_num == strlen(debugpath)) {
389 for (i = 0; i < history_num; i++) {
390 unsigned char c = info_to_arg[history[i].type];
393 if (c != debugpath[i])
396 if (i == history_num) {
400 signal(SIGUSR1, SIG_IGN);
401 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
403 if (system(str) == 0)
409 switch (failtest_hook(history, history_num)) {
416 /* Already down probe path? Stop now. */
418 failtest_cleanup(true, 0);
419 /* FIXME: We should run *parent* and run probe until
420 * calls match up again. */
428 files = save_files();
430 /* We're going to fail in the child. */
432 if (pipe(control) != 0 || pipe(output) != 0)
433 err(1, "opening pipe");
435 /* Prevent double-printing (in child and parent) */
439 err(1, "forking failed");
445 gettimeofday(&now, NULL);
446 if (now.tv_usec < start.tv_usec) {
448 now.tv_usec += 1000000;
450 now.tv_usec -= start.tv_usec;
451 now.tv_sec -= start.tv_sec;
452 p = failpath_string();
453 trace("%u->%u (%u.%02u): %s (", getppid(), getpid(),
454 (int)now.tv_sec, (int)now.tv_usec / 10000, p);
456 p = strrchr(history[history_num-1].file, '/');
460 trace("%s", history[history_num-1].file);
461 trace(":%u)\n", history[history_num-1].line);
465 dup2(output[1], STDOUT_FILENO);
466 dup2(output[1], STDERR_FILENO);
467 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
469 control_fd = control[1];
473 signal(SIGUSR1, hand_down);
478 /* We grab output so we can display it; we grab writes so we
481 struct pollfd pfd[2];
484 pfd[0].fd = output[0];
485 pfd[0].events = POLLIN|POLLHUP;
486 pfd[1].fd = control[0];
487 pfd[1].events = POLLIN|POLLHUP;
490 ret = poll(pfd, 1, failtest_timeout_ms);
492 ret = poll(pfd, 2, failtest_timeout_ms);
499 err(1, "Poll returned %i", ret);
502 if (pfd[0].revents & POLLIN) {
505 out = realloc(out, outlen + 8192);
506 len = read(output[0], out + outlen, 8192);
508 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
509 if (read_all(control[0], &type, sizeof(type))) {
511 if (!read_write_info(control[0]))
513 } else if (type == RELEASE_LOCKS) {
515 /* FIXME: Tell them we're done... */
518 } else if (pfd[0].revents & POLLHUP) {
521 } while (type != FAILURE);
525 waitpid(child, &status, 0);
526 if (!WIFEXITED(status)) {
527 if (WTERMSIG(status) == SIGUSR1)
528 child_fail(out, outlen, "Timed out");
530 child_fail(out, outlen, "Killed by signal %u: ",
533 /* Child printed failure already, just pass up exit code. */
534 if (type == FAILURE) {
535 fprintf(stderr, "%.*s", (int)outlen, out);
537 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
539 if (WEXITSTATUS(status) != 0)
540 child_fail(out, outlen, "Exited with status %i: ",
541 WEXITSTATUS(status));
544 signal(SIGUSR1, SIG_DFL);
546 restore_files(files);
548 /* We continue onwards without failing. */
553 static void cleanup_calloc(struct calloc_call *call)
558 void *failtest_calloc(size_t nmemb, size_t size,
559 const char *file, unsigned line)
561 struct failtest_call *p;
562 struct calloc_call call;
565 p = add_history(FAILTEST_CALLOC, file, line, &call);
567 if (should_fail(p)) {
568 p->u.calloc.ret = NULL;
571 p->u.calloc.ret = calloc(nmemb, size);
572 set_cleanup(p, cleanup_calloc, struct calloc_call);
575 return p->u.calloc.ret;
578 static void cleanup_malloc(struct malloc_call *call)
583 void *failtest_malloc(size_t size, const char *file, unsigned line)
585 struct failtest_call *p;
586 struct malloc_call call;
589 p = add_history(FAILTEST_MALLOC, file, line, &call);
590 if (should_fail(p)) {
591 p->u.calloc.ret = NULL;
594 p->u.calloc.ret = malloc(size);
595 set_cleanup(p, cleanup_malloc, struct malloc_call);
598 return p->u.calloc.ret;
601 static void cleanup_realloc(struct realloc_call *call)
606 /* Walk back and find out if we got this ptr from a previous routine. */
607 static void fixup_ptr_history(void *ptr, unsigned int last)
611 /* Start at end of history, work back. */
612 for (i = last - 1; i >= 0; i--) {
613 switch (history[i].type) {
614 case FAILTEST_REALLOC:
615 if (history[i].u.realloc.ret == ptr) {
616 history[i].cleanup = NULL;
620 case FAILTEST_MALLOC:
621 if (history[i].u.malloc.ret == ptr) {
622 history[i].cleanup = NULL;
626 case FAILTEST_CALLOC:
627 if (history[i].u.calloc.ret == ptr) {
628 history[i].cleanup = NULL;
638 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
640 struct failtest_call *p;
641 struct realloc_call call;
643 p = add_history(FAILTEST_REALLOC, file, line, &call);
645 /* FIXME: Try one child moving allocation, one not. */
646 if (should_fail(p)) {
647 p->u.realloc.ret = NULL;
650 fixup_ptr_history(ptr, history_num-1);
651 p->u.realloc.ret = realloc(ptr, size);
652 set_cleanup(p, cleanup_realloc, struct realloc_call);
655 return p->u.realloc.ret;
658 void failtest_free(void *ptr)
660 fixup_ptr_history(ptr, history_num);
664 static void cleanup_open(struct open_call *call)
669 int failtest_open(const char *pathname,
670 const char *file, unsigned line, ...)
672 struct failtest_call *p;
673 struct open_call call;
676 call.pathname = strdup(pathname);
678 call.flags = va_arg(ap, int);
679 if (call.flags & O_CREAT) {
680 call.mode = va_arg(ap, int);
683 p = add_history(FAILTEST_OPEN, file, line, &call);
684 /* Avoid memory leak! */
685 if (p == &unrecorded_call)
686 free((char *)call.pathname);
687 p->u.open.ret = open(pathname, call.flags, call.mode);
689 if (!failpath && p->u.open.ret == -1) {
692 } else if (should_fail(p)) {
693 close(p->u.open.ret);
695 /* FIXME: Play with error codes? */
698 set_cleanup(p, cleanup_open, struct open_call);
701 return p->u.open.ret;
704 static void cleanup_pipe(struct pipe_call *call)
706 if (!call->closed[0])
708 if (!call->closed[1])
712 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
714 struct failtest_call *p;
715 struct pipe_call call;
717 p = add_history(FAILTEST_PIPE, file, line, &call);
718 if (should_fail(p)) {
720 /* FIXME: Play with error codes? */
723 p->u.pipe.ret = pipe(p->u.pipe.fds);
724 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
725 set_cleanup(p, cleanup_pipe, struct pipe_call);
727 /* This causes valgrind to notice if they use pipefd[] after failure */
728 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
730 return p->u.pipe.ret;
733 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
734 const char *file, unsigned line)
736 struct failtest_call *p;
737 struct read_call call;
742 p = add_history(FAILTEST_READ, file, line, &call);
744 /* FIXME: Try partial read returns. */
745 if (should_fail(p)) {
749 p->u.read.ret = pread(fd, buf, count, off);
752 return p->u.read.ret;
755 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
756 const char *file, unsigned line)
758 struct failtest_call *p;
759 struct write_call call;
765 p = add_history(FAILTEST_WRITE, file, line, &call);
767 /* If we're a child, we need to make sure we write the same thing
768 * to non-files as the parent does, so tell it. */
769 if (control_fd != -1 && off == (off_t)-1) {
770 enum info_type type = WRITE;
772 write_all(control_fd, &type, sizeof(type));
773 write_all(control_fd, &p->u.write, sizeof(p->u.write));
774 write_all(control_fd, buf, count);
777 /* FIXME: Try partial write returns. */
778 if (should_fail(p)) {
782 /* FIXME: We assume same write order in parent and child */
783 if (off == (off_t)-1 && child_writes_num != 0) {
784 if (child_writes[0].fd != fd)
785 errx(1, "Child wrote to fd %u, not %u?",
786 child_writes[0].fd, fd);
787 if (child_writes[0].off != p->u.write.off)
788 errx(1, "Child wrote to offset %zu, not %zu?",
789 (size_t)child_writes[0].off,
790 (size_t)p->u.write.off);
791 if (child_writes[0].count != count)
792 errx(1, "Child wrote length %zu, not %zu?",
793 child_writes[0].count, count);
794 if (memcmp(child_writes[0].buf, buf, count)) {
796 "Child wrote differently to"
797 " fd %u than we did!\n", fd);
799 free((char *)child_writes[0].buf);
801 memmove(&child_writes[0], &child_writes[1],
802 sizeof(child_writes[0]) * child_writes_num);
804 /* Is this is a socket or pipe, child wrote it
806 if (p->u.write.off == (off_t)-1) {
807 p->u.write.ret = count;
809 return p->u.write.ret;
812 p->u.write.ret = pwrite(fd, buf, count, off);
815 return p->u.write.ret;
818 ssize_t failtest_read(int fd, void *buf, size_t count,
819 const char *file, unsigned line)
821 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
825 ssize_t failtest_write(int fd, const void *buf, size_t count,
826 const char *file, unsigned line)
828 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
832 static struct lock_info *WARN_UNUSED_RESULT
833 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
838 for (i = 0; i < lock_num; i++) {
843 /* Four cases we care about:
857 if (start > l->start && end < l->end) {
858 /* Mid overlap: trim entry, add new one. */
859 off_t new_start, new_end;
863 locks = add_lock(locks,
864 fd, new_start, new_end, l->type);
866 } else if (start <= l->start && end >= l->end) {
867 /* Total overlap: eliminate entry. */
870 } else if (end >= l->start && end < l->end) {
871 /* Start overlap: trim entry. */
873 } else if (start > l->start && start <= l->end) {
874 /* End overlap: trim entry. */
877 /* Nothing left? Remove it. */
878 if (l->end < l->start) {
879 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
884 if (type != F_UNLCK) {
885 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
886 l = &locks[lock_num++];
895 /* We trap this so we can record it: we don't fail it. */
896 int failtest_close(int fd, const char *file, unsigned line)
899 struct close_call call;
900 struct failtest_call *p;
903 p = add_history(FAILTEST_CLOSE, file, line, &call);
906 /* Consume close from failpath. */
914 /* Trace history to find source of fd. */
915 for (i = history_num-1; i >= 0; i--) {
916 switch (history[i].type) {
919 if (history[i].u.pipe.fds[0] == fd) {
920 assert(!history[i].u.pipe.closed[0]);
921 history[i].u.pipe.closed[0] = true;
922 if (history[i].u.pipe.closed[1])
923 history[i].cleanup = NULL;
926 if (history[i].u.pipe.fds[1] == fd) {
927 assert(!history[i].u.pipe.closed[1]);
928 history[i].u.pipe.closed[1] = true;
929 if (history[i].u.pipe.closed[0])
930 history[i].cleanup = NULL;
935 if (history[i].u.open.ret == fd) {
936 assert((void *)history[i].cleanup
937 == (void *)cleanup_open);
938 history[i].cleanup = NULL;
948 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
952 /* Zero length means "to end of file" */
953 static off_t end_of(off_t start, off_t len)
957 return start + len - 1;
960 /* FIXME: This only handles locks, really. */
961 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
963 struct failtest_call *p;
964 struct fcntl_call call;
970 /* Argument extraction. */
975 call.arg.l = va_arg(ap, long);
977 return fcntl(fd, cmd, call.arg.l);
980 return fcntl(fd, cmd);
984 call.arg.fl = *va_arg(ap, struct flock *);
986 return fcntl(fd, cmd, &call.arg.fl);
990 call.arg.fl = *va_arg(ap, struct flock *);
994 /* This means you need to implement it here. */
995 err(1, "failtest: unknown fcntl %u", cmd);
998 p = add_history(FAILTEST_FCNTL, file, line, &call);
1000 if (should_fail(p)) {
1001 p->u.fcntl.ret = -1;
1002 if (p->u.fcntl.cmd == F_SETLK)
1008 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
1009 &p->u.fcntl.arg.fl);
1010 if (p->u.fcntl.ret == -1)
1013 /* We don't handle anything else yet. */
1014 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1015 locks = add_lock(locks,
1017 p->u.fcntl.arg.fl.l_start,
1018 end_of(p->u.fcntl.arg.fl.l_start,
1019 p->u.fcntl.arg.fl.l_len),
1020 p->u.fcntl.arg.fl.l_type);
1024 return p->u.fcntl.ret;
1027 void failtest_init(int argc, char *argv[])
1031 for (i = 1; i < argc; i++) {
1032 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1033 failpath = argv[i] + strlen("--failpath=");
1034 } else if (strcmp(argv[i], "--tracepath") == 0) {
1035 tracefd = dup(STDERR_FILENO);
1036 failtest_timeout_ms = -1;
1037 } else if (!strncmp(argv[i], "--debugpath=",
1038 strlen("--debugpath="))) {
1039 debugpath = argv[i] + strlen("--debugpath=");
1042 gettimeofday(&start, NULL);
1045 void failtest_exit(int status)
1047 if (failtest_exit_check) {
1048 if (!failtest_exit_check(history, history_num))
1049 child_fail(NULL, 0, "failtest_exit_check failed\n");
1052 failtest_cleanup(false, status);