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 #define set_cleanup(call, clean, type) \
88 (call)->cleanup = (void *)((void)sizeof(clean((type *)NULL)), (clean))
90 static bool read_write_info(int fd)
95 /* We don't need all of this, but it's simple. */
96 child_writes = realloc(child_writes,
97 (child_writes_num+1) * sizeof(child_writes[0]));
98 w = &child_writes[child_writes_num];
99 if (!read_all(fd, w, sizeof(*w)))
102 w->buf = buf = malloc(w->count);
103 if (!read_all(fd, buf, w->count))
110 static char *failpath_string(void)
113 char *ret = malloc(history_num + 1);
115 for (i = 0; i < history_num; i++) {
116 ret[i] = info_to_arg[history[i].type];
118 ret[i] = toupper(ret[i]);
124 static void tell_parent(enum info_type type)
126 if (control_fd != -1)
127 write_all(control_fd, &type, sizeof(type));
130 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
133 char *path = failpath_string();
136 vfprintf(stderr, fmt, ap);
139 fprintf(stderr, "%.*s", (int)outlen, out);
140 printf("To reproduce: --failpath=%s\n", path);
142 tell_parent(FAILURE);
146 static void trace(const char *fmt, ...)
154 vdprintf(tracefd, fmt, ap);
160 static void hand_down(int signum)
165 static void release_locks(void)
167 /* Locks were never acquired/reacquired? */
171 /* We own them? Release them all. */
172 if (lock_owner == getpid()) {
176 fl.l_whence = SEEK_SET;
180 for (i = 0; i < lock_num; i++)
181 fcntl(locks[i].fd, F_SETLK, &fl);
183 /* Our parent must have them; pass request up. */
184 enum info_type type = RELEASE_LOCKS;
185 assert(control_fd != -1);
186 write_all(control_fd, &type, sizeof(type));
191 /* off_t is a signed type. Getting its max is non-trivial. */
192 static off_t off_max(void)
194 BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
195 if (sizeof(off_t) == 4)
196 return (off_t)0x7FFFFFF;
198 return (off_t)0x7FFFFFFFFFFFFFFULL;
201 static void get_locks(void)
206 if (lock_owner == getpid())
209 if (lock_owner != 0) {
210 enum info_type type = RELEASE_LOCKS;
211 assert(control_fd != -1);
212 write_all(control_fd, &type, sizeof(type));
215 fl.l_whence = SEEK_SET;
217 for (i = 0; i < lock_num; i++) {
218 fl.l_type = locks[i].type;
219 fl.l_start = locks[i].start;
220 if (locks[i].end == off_max())
223 fl.l_len = locks[i].end - locks[i].start + 1;
225 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
228 lock_owner = getpid();
232 struct saved_file *next;
238 static struct saved_file *save_file(struct saved_file *next, int fd)
240 struct saved_file *s = malloc(sizeof(*s));
244 s->off = lseek(fd, 0, SEEK_CUR);
245 /* Special file? Erk... */
246 assert(s->off != -1);
247 s->len = lseek(fd, 0, SEEK_END);
248 lseek(fd, 0, SEEK_SET);
249 s->contents = malloc(s->len);
250 read(fd, s->contents, s->len);
251 lseek(fd, s->off, SEEK_SET);
255 /* We have little choice but to save and restore open files: mmap means we
256 * can really intercept changes in the child.
258 * We could do non-mmap'ed files on demand, however. */
259 static struct saved_file *save_files(void)
261 struct saved_file *files = NULL;
264 /* Figure out the set of live fds. */
265 for (i = history_num - 2; i >= 0; i--) {
266 if (history[i].type == FAILTEST_OPEN) {
267 int fd = history[i].u.open.ret;
268 /* Only do successful, writable fds. */
272 /* If it was closed, cleanup == NULL. */
273 if (!history[i].cleanup)
276 if ((history[i].u.open.flags & O_RDWR) == O_RDWR) {
277 files = save_file(files, fd);
278 } else if ((history[i].u.open.flags & O_WRONLY)
280 /* FIXME: Handle O_WRONLY. Open with O_RDWR? */
289 static void restore_files(struct saved_file *s)
292 struct saved_file *next = s->next;
294 lseek(s->fd, 0, SEEK_SET);
295 write(s->fd, s->contents, s->len);
296 ftruncate(s->fd, s->len);
298 lseek(s->fd, s->off, SEEK_SET);
304 /* Free up memory, so valgrind doesn't report leaks. */
305 static void free_everything(void)
309 /* We don't do this in cleanup: needed even for failed opens. */
310 for (i = 0; i < history_num; i++) {
311 if (history[i].type == FAILTEST_OPEN)
312 free((char *)history[i].u.open.pathname);
317 static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
321 /* For children, we don't care if they "failed" the testing. */
322 if (control_fd != -1)
328 /* Cleanup everything, in reverse order. */
329 for (i = history_num - 1; i >= 0; i--) {
330 if (!history[i].cleanup)
332 if (!forced_cleanup) {
333 printf("Leak at %s:%u\n",
334 history[i].file, history[i].line);
337 history[i].cleanup(&history[i].u);
341 tell_parent(SUCCESS);
345 static bool should_fail(struct failtest_call *call)
348 int control[2], output[2];
349 enum info_type type = UNEXPECTED;
352 struct saved_file *files;
354 /* Are we probing? */
355 if (probe_count && --probe_count == 0)
356 failtest_cleanup(true, 0);
358 if (call == &unrecorded_call)
362 /* + means continue after end, like normal. */
363 if (*failpath == '+')
366 if (tolower(*failpath) != info_to_arg[call->type])
367 errx(1, "Failpath expected '%c' got '%c'\n",
368 info_to_arg[call->type], *failpath);
369 call->fail = isupper(*(failpath++));
374 /* Attach debugger if they asked for it. */
375 if (debugpath && history_num == strlen(debugpath)) {
378 for (i = 0; i < history_num; i++) {
379 char c = info_to_arg[history[i].type];
382 if (c != debugpath[i])
385 if (i == history_num) {
389 signal(SIGUSR1, SIG_IGN);
390 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
398 switch (failtest_hook(history, history_num)) {
405 /* Already down probe path? Stop now. */
407 failtest_cleanup(true, 0);
408 /* FIXME: We should run *parent* and run probe until
409 * calls match up again. */
417 files = save_files();
419 /* We're going to fail in the child. */
421 if (pipe(control) != 0 || pipe(output) != 0)
422 err(1, "opening pipe");
424 /* Prevent double-printing (in child and parent) */
428 err(1, "forking failed");
434 gettimeofday(&now, NULL);
435 if (now.tv_usec < start.tv_usec) {
437 now.tv_usec += 1000000;
439 now.tv_usec -= start.tv_usec;
440 now.tv_sec -= start.tv_sec;
441 p = failpath_string();
442 trace("%u->%u (%u.%02u): %s (", getppid(), getpid(),
443 (int)now.tv_sec, (int)now.tv_usec / 10000, p);
445 p = strrchr(history[history_num-1].file, '/');
449 trace("%s", history[history_num-1].file);
450 trace(":%u)\n", history[history_num-1].line);
454 dup2(output[1], STDOUT_FILENO);
455 dup2(output[1], STDERR_FILENO);
456 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
458 control_fd = control[1];
462 signal(SIGUSR1, hand_down);
467 /* We grab output so we can display it; we grab writes so we
470 struct pollfd pfd[2];
473 pfd[0].fd = output[0];
474 pfd[0].events = POLLIN|POLLHUP;
475 pfd[1].fd = control[0];
476 pfd[1].events = POLLIN|POLLHUP;
479 ret = poll(pfd, 1, failtest_timeout_ms);
481 ret = poll(pfd, 2, failtest_timeout_ms);
486 if (pfd[0].revents & POLLIN) {
489 out = realloc(out, outlen + 8192);
490 len = read(output[0], out + outlen, 8192);
492 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
493 if (read_all(control[0], &type, sizeof(type))) {
495 if (!read_write_info(control[0]))
497 } else if (type == RELEASE_LOCKS) {
499 /* FIXME: Tell them we're done... */
502 } else if (pfd[0].revents & POLLHUP) {
505 } while (type != FAILURE);
509 waitpid(child, &status, 0);
510 if (!WIFEXITED(status)) {
511 if (WTERMSIG(status) == SIGUSR1)
512 child_fail(out, outlen, "Timed out");
514 child_fail(out, outlen, "Killed by signal %u: ",
517 /* Child printed failure already, just pass up exit code. */
518 if (type == FAILURE) {
519 fprintf(stderr, "%.*s", (int)outlen, out);
521 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
523 if (WEXITSTATUS(status) != 0)
524 child_fail(out, outlen, "Exited with status %i: ",
525 WEXITSTATUS(status));
528 signal(SIGUSR1, SIG_DFL);
530 restore_files(files);
532 /* We continue onwards without failing. */
537 static void cleanup_calloc(struct calloc_call *call)
542 void *failtest_calloc(size_t nmemb, size_t size,
543 const char *file, unsigned line)
545 struct failtest_call *p;
546 struct calloc_call call;
549 p = add_history(FAILTEST_CALLOC, file, line, &call);
551 if (should_fail(p)) {
552 p->u.calloc.ret = NULL;
555 p->u.calloc.ret = calloc(nmemb, size);
556 set_cleanup(p, cleanup_calloc, struct calloc_call);
559 return p->u.calloc.ret;
562 static void cleanup_malloc(struct malloc_call *call)
567 void *failtest_malloc(size_t size, const char *file, unsigned line)
569 struct failtest_call *p;
570 struct malloc_call call;
573 p = add_history(FAILTEST_MALLOC, file, line, &call);
574 if (should_fail(p)) {
575 p->u.calloc.ret = NULL;
578 p->u.calloc.ret = malloc(size);
579 set_cleanup(p, cleanup_malloc, struct malloc_call);
582 return p->u.calloc.ret;
585 static void cleanup_realloc(struct realloc_call *call)
590 /* Walk back and find out if we got this ptr from a previous routine. */
591 static void fixup_ptr_history(void *ptr, unsigned int last)
595 /* Start at end of history, work back. */
596 for (i = last - 1; i >= 0; i--) {
597 switch (history[i].type) {
598 case FAILTEST_REALLOC:
599 if (history[i].u.realloc.ret == ptr) {
600 history[i].cleanup = NULL;
604 case FAILTEST_MALLOC:
605 if (history[i].u.malloc.ret == ptr) {
606 history[i].cleanup = NULL;
610 case FAILTEST_CALLOC:
611 if (history[i].u.calloc.ret == ptr) {
612 history[i].cleanup = NULL;
622 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
624 struct failtest_call *p;
625 struct realloc_call call;
627 p = add_history(FAILTEST_REALLOC, file, line, &call);
629 /* FIXME: Try one child moving allocation, one not. */
630 if (should_fail(p)) {
631 p->u.realloc.ret = NULL;
634 fixup_ptr_history(ptr, history_num-1);
635 p->u.realloc.ret = realloc(ptr, size);
636 set_cleanup(p, cleanup_realloc, struct realloc_call);
639 return p->u.realloc.ret;
642 void failtest_free(void *ptr)
644 fixup_ptr_history(ptr, history_num);
648 static void cleanup_open(struct open_call *call)
653 int failtest_open(const char *pathname,
654 const char *file, unsigned line, ...)
656 struct failtest_call *p;
657 struct open_call call;
660 call.pathname = strdup(pathname);
662 call.flags = va_arg(ap, int);
663 if (call.flags & O_CREAT) {
664 call.mode = va_arg(ap, mode_t);
667 p = add_history(FAILTEST_OPEN, file, line, &call);
668 /* Avoid memory leak! */
669 if (p == &unrecorded_call)
670 free((char *)call.pathname);
671 p->u.open.ret = open(pathname, call.flags, call.mode);
673 if (!failpath && p->u.open.ret == -1) {
676 } else if (should_fail(p)) {
677 close(p->u.open.ret);
679 /* FIXME: Play with error codes? */
682 set_cleanup(p, cleanup_open, struct open_call);
685 return p->u.open.ret;
688 static void cleanup_pipe(struct pipe_call *call)
690 if (!call->closed[0])
692 if (!call->closed[1])
696 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
698 struct failtest_call *p;
699 struct pipe_call call;
701 p = add_history(FAILTEST_PIPE, file, line, &call);
702 if (should_fail(p)) {
704 /* FIXME: Play with error codes? */
707 p->u.pipe.ret = pipe(p->u.pipe.fds);
708 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
709 set_cleanup(p, cleanup_pipe, struct pipe_call);
711 /* This causes valgrind to notice if they use pipefd[] after failure */
712 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
714 return p->u.pipe.ret;
717 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
718 const char *file, unsigned line)
720 struct failtest_call *p;
721 struct read_call call;
726 p = add_history(FAILTEST_READ, file, line, &call);
728 /* FIXME: Try partial read returns. */
729 if (should_fail(p)) {
733 p->u.read.ret = pread(fd, buf, count, off);
736 return p->u.read.ret;
739 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
740 const char *file, unsigned line)
742 struct failtest_call *p;
743 struct write_call call;
749 p = add_history(FAILTEST_WRITE, file, line, &call);
751 /* If we're a child, we need to make sure we write the same thing
752 * to non-files as the parent does, so tell it. */
753 if (control_fd != -1 && off == (off_t)-1) {
754 enum info_type type = WRITE;
756 write_all(control_fd, &type, sizeof(type));
757 write_all(control_fd, &p->u.write, sizeof(p->u.write));
758 write_all(control_fd, buf, count);
761 /* FIXME: Try partial write returns. */
762 if (should_fail(p)) {
766 /* FIXME: We assume same write order in parent and child */
767 if (off == (off_t)-1 && child_writes_num != 0) {
768 if (child_writes[0].fd != fd)
769 errx(1, "Child wrote to fd %u, not %u?",
770 child_writes[0].fd, fd);
771 if (child_writes[0].off != p->u.write.off)
772 errx(1, "Child wrote to offset %zu, not %zu?",
773 (size_t)child_writes[0].off,
774 (size_t)p->u.write.off);
775 if (child_writes[0].count != count)
776 errx(1, "Child wrote length %zu, not %zu?",
777 child_writes[0].count, count);
778 if (memcmp(child_writes[0].buf, buf, count)) {
780 "Child wrote differently to"
781 " fd %u than we did!\n", fd);
783 free((char *)child_writes[0].buf);
785 memmove(&child_writes[0], &child_writes[1],
786 sizeof(child_writes[0]) * child_writes_num);
788 /* Is this is a socket or pipe, child wrote it
790 if (p->u.write.off == (off_t)-1) {
791 p->u.write.ret = count;
793 return p->u.write.ret;
796 p->u.write.ret = pwrite(fd, buf, count, off);
799 return p->u.write.ret;
802 ssize_t failtest_read(int fd, void *buf, size_t count,
803 const char *file, unsigned line)
805 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
809 ssize_t failtest_write(int fd, const void *buf, size_t count,
810 const char *file, unsigned line)
812 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
816 static struct lock_info *WARN_UNUSED_RESULT
817 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
822 for (i = 0; i < lock_num; i++) {
827 /* Four cases we care about:
841 if (start > l->start && end < l->end) {
842 /* Mid overlap: trim entry, add new one. */
843 off_t new_start, new_end;
847 locks = add_lock(locks,
848 fd, new_start, new_end, l->type);
850 } else if (start <= l->start && end >= l->end) {
851 /* Total overlap: eliminate entry. */
854 } else if (end >= l->start && end < l->end) {
855 /* Start overlap: trim entry. */
857 } else if (start > l->start && start <= l->end) {
858 /* End overlap: trim entry. */
861 /* Nothing left? Remove it. */
862 if (l->end < l->start) {
863 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
868 if (type != F_UNLCK) {
869 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
870 l = &locks[lock_num++];
879 /* We trap this so we can record it: we don't fail it. */
880 int failtest_close(int fd, const char *file, unsigned line)
883 struct close_call call;
884 struct failtest_call *p;
887 p = add_history(FAILTEST_CLOSE, file, line, &call);
890 /* Consume close from failpath. */
898 /* Trace history to find source of fd. */
899 for (i = history_num-1; i >= 0; i--) {
900 switch (history[i].type) {
903 if (history[i].u.pipe.fds[0] == fd) {
904 assert(!history[i].u.pipe.closed[0]);
905 history[i].u.pipe.closed[0] = true;
906 if (history[i].u.pipe.closed[1])
907 history[i].cleanup = NULL;
910 if (history[i].u.pipe.fds[1] == fd) {
911 assert(!history[i].u.pipe.closed[1]);
912 history[i].u.pipe.closed[1] = true;
913 if (history[i].u.pipe.closed[0])
914 history[i].cleanup = NULL;
919 if (history[i].u.open.ret == fd) {
920 assert((void *)history[i].cleanup
921 == (void *)cleanup_open);
922 history[i].cleanup = NULL;
932 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
936 /* Zero length means "to end of file" */
937 static off_t end_of(off_t start, off_t len)
941 return start + len - 1;
944 /* FIXME: This only handles locks, really. */
945 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
947 struct failtest_call *p;
948 struct fcntl_call call;
954 /* Argument extraction. */
959 call.arg.l = va_arg(ap, long);
961 return fcntl(fd, cmd, call.arg.l);
964 return fcntl(fd, cmd);
968 call.arg.fl = *va_arg(ap, struct flock *);
970 return fcntl(fd, cmd, &call.arg.fl);
974 call.arg.fl = *va_arg(ap, struct flock *);
978 /* This means you need to implement it here. */
979 err(1, "failtest: unknown fcntl %u", cmd);
982 p = add_history(FAILTEST_FCNTL, file, line, &call);
984 if (should_fail(p)) {
986 if (p->u.fcntl.cmd == F_SETLK)
992 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
994 if (p->u.fcntl.ret == -1)
997 /* We don't handle anything else yet. */
998 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
999 locks = add_lock(locks,
1001 p->u.fcntl.arg.fl.l_start,
1002 end_of(p->u.fcntl.arg.fl.l_start,
1003 p->u.fcntl.arg.fl.l_len),
1004 p->u.fcntl.arg.fl.l_type);
1008 return p->u.fcntl.ret;
1011 void failtest_init(int argc, char *argv[])
1015 for (i = 1; i < argc; i++) {
1016 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1017 failpath = argv[i] + strlen("--failpath=");
1018 } else if (strcmp(argv[i], "--tracepath") == 0) {
1019 tracefd = dup(STDERR_FILENO);
1020 failtest_timeout_ms = -1;
1021 } else if (!strncmp(argv[i], "--debugpath=",
1022 strlen("--debugpath="))) {
1023 debugpath = argv[i] + strlen("--debugpath=");
1026 gettimeofday(&start, NULL);
1029 void failtest_exit(int status)
1031 if (failtest_exit_check) {
1032 if (!failtest_exit_check(history, history_num))
1033 child_fail(NULL, 0, "failtest_exit_check failed\n");
1036 failtest_cleanup(false, status);