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 read(fd, s->contents, s->len);
252 lseek(fd, s->off, SEEK_SET);
256 /* We have little choice but to save and restore open files: mmap means we
257 * can really intercept changes in the child.
259 * We could do non-mmap'ed files on demand, however. */
260 static struct saved_file *save_files(void)
262 struct saved_file *files = NULL;
265 /* Figure out the set of live fds. */
266 for (i = history_num - 2; i >= 0; i--) {
267 if (history[i].type == FAILTEST_OPEN) {
268 int fd = history[i].u.open.ret;
269 /* Only do successful, writable fds. */
273 /* If it was closed, cleanup == NULL. */
274 if (!history[i].cleanup)
277 if ((history[i].u.open.flags & O_RDWR) == O_RDWR) {
278 files = save_file(files, fd);
279 } else if ((history[i].u.open.flags & O_WRONLY)
281 /* FIXME: Handle O_WRONLY. Open with O_RDWR? */
290 static void restore_files(struct saved_file *s)
293 struct saved_file *next = s->next;
295 lseek(s->fd, 0, SEEK_SET);
296 write(s->fd, s->contents, s->len);
297 ftruncate(s->fd, s->len);
299 lseek(s->fd, s->off, SEEK_SET);
305 /* Free up memory, so valgrind doesn't report leaks. */
306 static void free_everything(void)
310 /* We don't do this in cleanup: needed even for failed opens. */
311 for (i = 0; i < history_num; i++) {
312 if (history[i].type == FAILTEST_OPEN)
313 free((char *)history[i].u.open.pathname);
318 static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
322 /* For children, we don't care if they "failed" the testing. */
323 if (control_fd != -1)
329 /* Cleanup everything, in reverse order. */
330 for (i = history_num - 1; i >= 0; i--) {
331 if (!history[i].cleanup)
333 if (!forced_cleanup) {
334 printf("Leak at %s:%u: --failpath=%s\n",
335 history[i].file, history[i].line,
339 history[i].cleanup(&history[i].u);
343 tell_parent(SUCCESS);
347 static bool should_fail(struct failtest_call *call)
350 int control[2], output[2];
351 enum info_type type = UNEXPECTED;
354 struct saved_file *files;
356 /* Are we probing? */
357 if (probe_count && --probe_count == 0)
358 failtest_cleanup(true, 0);
360 if (call == &unrecorded_call)
364 /* + means continue after end, like normal. */
365 if (*failpath == '+')
368 if (tolower((unsigned char)*failpath)
369 != info_to_arg[call->type])
370 errx(1, "Failpath expected '%c' got '%c'\n",
371 info_to_arg[call->type], *failpath);
372 call->fail = isupper((unsigned char)*(failpath++));
377 /* Attach debugger if they asked for it. */
378 if (debugpath && history_num == strlen(debugpath)) {
381 for (i = 0; i < history_num; i++) {
382 unsigned char c = info_to_arg[history[i].type];
385 if (c != debugpath[i])
388 if (i == history_num) {
392 signal(SIGUSR1, SIG_IGN);
393 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
401 switch (failtest_hook(history, history_num)) {
408 /* Already down probe path? Stop now. */
410 failtest_cleanup(true, 0);
411 /* FIXME: We should run *parent* and run probe until
412 * calls match up again. */
420 files = save_files();
422 /* We're going to fail in the child. */
424 if (pipe(control) != 0 || pipe(output) != 0)
425 err(1, "opening pipe");
427 /* Prevent double-printing (in child and parent) */
431 err(1, "forking failed");
437 gettimeofday(&now, NULL);
438 if (now.tv_usec < start.tv_usec) {
440 now.tv_usec += 1000000;
442 now.tv_usec -= start.tv_usec;
443 now.tv_sec -= start.tv_sec;
444 p = failpath_string();
445 trace("%u->%u (%u.%02u): %s (", getppid(), getpid(),
446 (int)now.tv_sec, (int)now.tv_usec / 10000, p);
448 p = strrchr(history[history_num-1].file, '/');
452 trace("%s", history[history_num-1].file);
453 trace(":%u)\n", history[history_num-1].line);
457 dup2(output[1], STDOUT_FILENO);
458 dup2(output[1], STDERR_FILENO);
459 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
461 control_fd = control[1];
465 signal(SIGUSR1, hand_down);
470 /* We grab output so we can display it; we grab writes so we
473 struct pollfd pfd[2];
476 pfd[0].fd = output[0];
477 pfd[0].events = POLLIN|POLLHUP;
478 pfd[1].fd = control[0];
479 pfd[1].events = POLLIN|POLLHUP;
482 ret = poll(pfd, 1, failtest_timeout_ms);
484 ret = poll(pfd, 2, failtest_timeout_ms);
491 err(1, "Poll returned %i", ret);
494 if (pfd[0].revents & POLLIN) {
497 out = realloc(out, outlen + 8192);
498 len = read(output[0], out + outlen, 8192);
500 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
501 if (read_all(control[0], &type, sizeof(type))) {
503 if (!read_write_info(control[0]))
505 } else if (type == RELEASE_LOCKS) {
507 /* FIXME: Tell them we're done... */
510 } else if (pfd[0].revents & POLLHUP) {
513 } while (type != FAILURE);
517 waitpid(child, &status, 0);
518 if (!WIFEXITED(status)) {
519 if (WTERMSIG(status) == SIGUSR1)
520 child_fail(out, outlen, "Timed out");
522 child_fail(out, outlen, "Killed by signal %u: ",
525 /* Child printed failure already, just pass up exit code. */
526 if (type == FAILURE) {
527 fprintf(stderr, "%.*s", (int)outlen, out);
529 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
531 if (WEXITSTATUS(status) != 0)
532 child_fail(out, outlen, "Exited with status %i: ",
533 WEXITSTATUS(status));
536 signal(SIGUSR1, SIG_DFL);
538 restore_files(files);
540 /* We continue onwards without failing. */
545 static void cleanup_calloc(struct calloc_call *call)
550 void *failtest_calloc(size_t nmemb, size_t size,
551 const char *file, unsigned line)
553 struct failtest_call *p;
554 struct calloc_call call;
557 p = add_history(FAILTEST_CALLOC, file, line, &call);
559 if (should_fail(p)) {
560 p->u.calloc.ret = NULL;
563 p->u.calloc.ret = calloc(nmemb, size);
564 set_cleanup(p, cleanup_calloc, struct calloc_call);
567 return p->u.calloc.ret;
570 static void cleanup_malloc(struct malloc_call *call)
575 void *failtest_malloc(size_t size, const char *file, unsigned line)
577 struct failtest_call *p;
578 struct malloc_call call;
581 p = add_history(FAILTEST_MALLOC, file, line, &call);
582 if (should_fail(p)) {
583 p->u.calloc.ret = NULL;
586 p->u.calloc.ret = malloc(size);
587 set_cleanup(p, cleanup_malloc, struct malloc_call);
590 return p->u.calloc.ret;
593 static void cleanup_realloc(struct realloc_call *call)
598 /* Walk back and find out if we got this ptr from a previous routine. */
599 static void fixup_ptr_history(void *ptr, unsigned int last)
603 /* Start at end of history, work back. */
604 for (i = last - 1; i >= 0; i--) {
605 switch (history[i].type) {
606 case FAILTEST_REALLOC:
607 if (history[i].u.realloc.ret == ptr) {
608 history[i].cleanup = NULL;
612 case FAILTEST_MALLOC:
613 if (history[i].u.malloc.ret == ptr) {
614 history[i].cleanup = NULL;
618 case FAILTEST_CALLOC:
619 if (history[i].u.calloc.ret == ptr) {
620 history[i].cleanup = NULL;
630 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
632 struct failtest_call *p;
633 struct realloc_call call;
635 p = add_history(FAILTEST_REALLOC, file, line, &call);
637 /* FIXME: Try one child moving allocation, one not. */
638 if (should_fail(p)) {
639 p->u.realloc.ret = NULL;
642 fixup_ptr_history(ptr, history_num-1);
643 p->u.realloc.ret = realloc(ptr, size);
644 set_cleanup(p, cleanup_realloc, struct realloc_call);
647 return p->u.realloc.ret;
650 void failtest_free(void *ptr)
652 fixup_ptr_history(ptr, history_num);
656 static void cleanup_open(struct open_call *call)
661 int failtest_open(const char *pathname,
662 const char *file, unsigned line, ...)
664 struct failtest_call *p;
665 struct open_call call;
668 call.pathname = strdup(pathname);
670 call.flags = va_arg(ap, int);
671 if (call.flags & O_CREAT) {
672 call.mode = va_arg(ap, mode_t);
675 p = add_history(FAILTEST_OPEN, file, line, &call);
676 /* Avoid memory leak! */
677 if (p == &unrecorded_call)
678 free((char *)call.pathname);
679 p->u.open.ret = open(pathname, call.flags, call.mode);
681 if (!failpath && p->u.open.ret == -1) {
684 } else if (should_fail(p)) {
685 close(p->u.open.ret);
687 /* FIXME: Play with error codes? */
690 set_cleanup(p, cleanup_open, struct open_call);
693 return p->u.open.ret;
696 static void cleanup_pipe(struct pipe_call *call)
698 if (!call->closed[0])
700 if (!call->closed[1])
704 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
706 struct failtest_call *p;
707 struct pipe_call call;
709 p = add_history(FAILTEST_PIPE, file, line, &call);
710 if (should_fail(p)) {
712 /* FIXME: Play with error codes? */
715 p->u.pipe.ret = pipe(p->u.pipe.fds);
716 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
717 set_cleanup(p, cleanup_pipe, struct pipe_call);
719 /* This causes valgrind to notice if they use pipefd[] after failure */
720 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
722 return p->u.pipe.ret;
725 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
726 const char *file, unsigned line)
728 struct failtest_call *p;
729 struct read_call call;
734 p = add_history(FAILTEST_READ, file, line, &call);
736 /* FIXME: Try partial read returns. */
737 if (should_fail(p)) {
741 p->u.read.ret = pread(fd, buf, count, off);
744 return p->u.read.ret;
747 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
748 const char *file, unsigned line)
750 struct failtest_call *p;
751 struct write_call call;
757 p = add_history(FAILTEST_WRITE, file, line, &call);
759 /* If we're a child, we need to make sure we write the same thing
760 * to non-files as the parent does, so tell it. */
761 if (control_fd != -1 && off == (off_t)-1) {
762 enum info_type type = WRITE;
764 write_all(control_fd, &type, sizeof(type));
765 write_all(control_fd, &p->u.write, sizeof(p->u.write));
766 write_all(control_fd, buf, count);
769 /* FIXME: Try partial write returns. */
770 if (should_fail(p)) {
774 /* FIXME: We assume same write order in parent and child */
775 if (off == (off_t)-1 && child_writes_num != 0) {
776 if (child_writes[0].fd != fd)
777 errx(1, "Child wrote to fd %u, not %u?",
778 child_writes[0].fd, fd);
779 if (child_writes[0].off != p->u.write.off)
780 errx(1, "Child wrote to offset %zu, not %zu?",
781 (size_t)child_writes[0].off,
782 (size_t)p->u.write.off);
783 if (child_writes[0].count != count)
784 errx(1, "Child wrote length %zu, not %zu?",
785 child_writes[0].count, count);
786 if (memcmp(child_writes[0].buf, buf, count)) {
788 "Child wrote differently to"
789 " fd %u than we did!\n", fd);
791 free((char *)child_writes[0].buf);
793 memmove(&child_writes[0], &child_writes[1],
794 sizeof(child_writes[0]) * child_writes_num);
796 /* Is this is a socket or pipe, child wrote it
798 if (p->u.write.off == (off_t)-1) {
799 p->u.write.ret = count;
801 return p->u.write.ret;
804 p->u.write.ret = pwrite(fd, buf, count, off);
807 return p->u.write.ret;
810 ssize_t failtest_read(int fd, void *buf, size_t count,
811 const char *file, unsigned line)
813 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
817 ssize_t failtest_write(int fd, const void *buf, size_t count,
818 const char *file, unsigned line)
820 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
824 static struct lock_info *WARN_UNUSED_RESULT
825 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
830 for (i = 0; i < lock_num; i++) {
835 /* Four cases we care about:
849 if (start > l->start && end < l->end) {
850 /* Mid overlap: trim entry, add new one. */
851 off_t new_start, new_end;
855 locks = add_lock(locks,
856 fd, new_start, new_end, l->type);
858 } else if (start <= l->start && end >= l->end) {
859 /* Total overlap: eliminate entry. */
862 } else if (end >= l->start && end < l->end) {
863 /* Start overlap: trim entry. */
865 } else if (start > l->start && start <= l->end) {
866 /* End overlap: trim entry. */
869 /* Nothing left? Remove it. */
870 if (l->end < l->start) {
871 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
876 if (type != F_UNLCK) {
877 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
878 l = &locks[lock_num++];
887 /* We trap this so we can record it: we don't fail it. */
888 int failtest_close(int fd, const char *file, unsigned line)
891 struct close_call call;
892 struct failtest_call *p;
895 p = add_history(FAILTEST_CLOSE, file, line, &call);
898 /* Consume close from failpath. */
906 /* Trace history to find source of fd. */
907 for (i = history_num-1; i >= 0; i--) {
908 switch (history[i].type) {
911 if (history[i].u.pipe.fds[0] == fd) {
912 assert(!history[i].u.pipe.closed[0]);
913 history[i].u.pipe.closed[0] = true;
914 if (history[i].u.pipe.closed[1])
915 history[i].cleanup = NULL;
918 if (history[i].u.pipe.fds[1] == fd) {
919 assert(!history[i].u.pipe.closed[1]);
920 history[i].u.pipe.closed[1] = true;
921 if (history[i].u.pipe.closed[0])
922 history[i].cleanup = NULL;
927 if (history[i].u.open.ret == fd) {
928 assert((void *)history[i].cleanup
929 == (void *)cleanup_open);
930 history[i].cleanup = NULL;
940 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
944 /* Zero length means "to end of file" */
945 static off_t end_of(off_t start, off_t len)
949 return start + len - 1;
952 /* FIXME: This only handles locks, really. */
953 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
955 struct failtest_call *p;
956 struct fcntl_call call;
962 /* Argument extraction. */
967 call.arg.l = va_arg(ap, long);
969 return fcntl(fd, cmd, call.arg.l);
972 return fcntl(fd, cmd);
976 call.arg.fl = *va_arg(ap, struct flock *);
978 return fcntl(fd, cmd, &call.arg.fl);
982 call.arg.fl = *va_arg(ap, struct flock *);
986 /* This means you need to implement it here. */
987 err(1, "failtest: unknown fcntl %u", cmd);
990 p = add_history(FAILTEST_FCNTL, file, line, &call);
992 if (should_fail(p)) {
994 if (p->u.fcntl.cmd == F_SETLK)
1000 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
1001 &p->u.fcntl.arg.fl);
1002 if (p->u.fcntl.ret == -1)
1005 /* We don't handle anything else yet. */
1006 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1007 locks = add_lock(locks,
1009 p->u.fcntl.arg.fl.l_start,
1010 end_of(p->u.fcntl.arg.fl.l_start,
1011 p->u.fcntl.arg.fl.l_len),
1012 p->u.fcntl.arg.fl.l_type);
1016 return p->u.fcntl.ret;
1019 void failtest_init(int argc, char *argv[])
1023 for (i = 1; i < argc; i++) {
1024 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1025 failpath = argv[i] + strlen("--failpath=");
1026 } else if (strcmp(argv[i], "--tracepath") == 0) {
1027 tracefd = dup(STDERR_FILENO);
1028 failtest_timeout_ms = -1;
1029 } else if (!strncmp(argv[i], "--debugpath=",
1030 strlen("--debugpath="))) {
1031 debugpath = argv[i] + strlen("--debugpath=");
1034 gettimeofday(&start, NULL);
1037 void failtest_exit(int status)
1039 if (failtest_exit_check) {
1040 if (!failtest_exit_check(history, history_num))
1041 child_fail(NULL, 0, "failtest_exit_check failed\n");
1044 failtest_cleanup(false, status);