1 /* Licensed under LGPL - see LICENSE file for details */
2 #include <ccan/failtest/failtest.h>
12 #include <sys/types.h>
18 #include <ccan/time/time.h>
19 #include <ccan/read_write_all/read_write_all.h>
20 #include <ccan/failtest/failtest_proto.h>
21 #include <ccan/build_assert/build_assert.h>
23 enum failtest_result (*failtest_hook)(struct failtest_call *, unsigned);
25 static int tracefd = -1;
27 unsigned int failtest_timeout_ms = 20000;
30 const char *debugpath;
42 /* end is inclusive: you can't have a 0-byte lock. */
47 bool (*failtest_exit_check)(struct failtest_call *history, unsigned num);
49 static struct failtest_call *history = NULL;
50 static unsigned int history_num = 0;
51 static int control_fd = -1;
52 static struct timeval start;
53 static unsigned int probe_count = 0;
55 static struct write_call *child_writes = NULL;
56 static unsigned int child_writes_num = 0;
58 static pid_t lock_owner;
59 static struct lock_info *locks = NULL;
60 static unsigned int lock_num = 0;
62 static pid_t orig_pid;
64 static const char info_to_arg[] = "mceoxprwf";
66 /* Dummy call used for failtest_undo wrappers. */
67 static struct failtest_call unrecorded_call;
69 static struct failtest_call *add_history_(enum failtest_call_type type,
75 /* NULL file is how we suppress failure. */
77 return &unrecorded_call;
79 history = realloc(history, (history_num + 1) * sizeof(*history));
80 history[history_num].type = type;
81 history[history_num].file = file;
82 history[history_num].line = line;
83 history[history_num].cleanup = NULL;
84 memcpy(&history[history_num].u, elem, elem_size);
85 return &history[history_num++];
88 #define add_history(type, file, line, elem) \
89 add_history_((type), (file), (line), (elem), sizeof(*(elem)))
91 /* We do a fake call inside a sizeof(), to check types. */
92 #define set_cleanup(call, clean, type) \
93 (call)->cleanup = (void *)((void)sizeof(clean((type *)NULL),1), (clean))
95 static bool read_write_info(int fd)
100 /* We don't need all of this, but it's simple. */
101 child_writes = realloc(child_writes,
102 (child_writes_num+1) * sizeof(child_writes[0]));
103 w = &child_writes[child_writes_num];
104 if (!read_all(fd, w, sizeof(*w)))
107 w->buf = buf = malloc(w->count);
108 if (!read_all(fd, buf, w->count))
115 static char *failpath_string(void)
118 char *ret = malloc(history_num + 1);
120 for (i = 0; i < history_num; i++) {
121 ret[i] = info_to_arg[history[i].type];
123 ret[i] = toupper(ret[i]);
129 static void tell_parent(enum info_type type)
131 if (control_fd != -1)
132 write_all(control_fd, &type, sizeof(type));
135 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
138 char *path = failpath_string();
141 vfprintf(stderr, fmt, ap);
144 fprintf(stderr, "%.*s", (int)outlen, out);
145 printf("To reproduce: --failpath=%s\n", path);
147 tell_parent(FAILURE);
151 static void trace(const char *fmt, ...)
159 vdprintf(tracefd, fmt, ap);
165 static void hand_down(int signum)
170 static void release_locks(void)
172 /* Locks were never acquired/reacquired? */
176 /* We own them? Release them all. */
177 if (lock_owner == getpid()) {
181 fl.l_whence = SEEK_SET;
185 for (i = 0; i < lock_num; i++)
186 fcntl(locks[i].fd, F_SETLK, &fl);
188 /* Our parent must have them; pass request up. */
189 enum info_type type = RELEASE_LOCKS;
190 assert(control_fd != -1);
191 write_all(control_fd, &type, sizeof(type));
196 /* off_t is a signed type. Getting its max is non-trivial. */
197 static off_t off_max(void)
199 BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
200 if (sizeof(off_t) == 4)
201 return (off_t)0x7FFFFFF;
203 return (off_t)0x7FFFFFFFFFFFFFFULL;
206 static void get_locks(void)
211 if (lock_owner == getpid())
214 if (lock_owner != 0) {
215 enum info_type type = RELEASE_LOCKS;
216 assert(control_fd != -1);
217 write_all(control_fd, &type, sizeof(type));
220 fl.l_whence = SEEK_SET;
222 for (i = 0; i < lock_num; i++) {
223 fl.l_type = locks[i].type;
224 fl.l_start = locks[i].start;
225 if (locks[i].end == off_max())
228 fl.l_len = locks[i].end - locks[i].start + 1;
230 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
233 lock_owner = getpid();
237 struct saved_file *next;
243 static struct saved_file *save_file(struct saved_file *next, int fd)
245 struct saved_file *s = malloc(sizeof(*s));
249 s->off = lseek(fd, 0, SEEK_CUR);
250 /* Special file? Erk... */
251 assert(s->off != -1);
252 s->len = lseek(fd, 0, SEEK_END);
253 lseek(fd, 0, SEEK_SET);
254 s->contents = malloc(s->len);
255 if (read(fd, s->contents, s->len) != s->len)
256 err(1, "Failed to save %zu bytes", (size_t)s->len);
257 lseek(fd, s->off, SEEK_SET);
261 /* We have little choice but to save and restore open files: mmap means we
262 * can really intercept changes in the child.
264 * We could do non-mmap'ed files on demand, however. */
265 static struct saved_file *save_files(void)
267 struct saved_file *files = NULL;
270 /* Figure out the set of live fds. */
271 for (i = history_num - 2; i >= 0; i--) {
272 if (history[i].type == FAILTEST_OPEN) {
273 int fd = history[i].u.open.ret;
274 /* Only do successful, writable fds. */
278 /* If it was closed, cleanup == NULL. */
279 if (!history[i].cleanup)
282 if ((history[i].u.open.flags & O_RDWR) == O_RDWR) {
283 files = save_file(files, fd);
284 } else if ((history[i].u.open.flags & O_WRONLY)
286 /* FIXME: Handle O_WRONLY. Open with O_RDWR? */
295 static void restore_files(struct saved_file *s)
298 struct saved_file *next = s->next;
300 lseek(s->fd, 0, SEEK_SET);
301 if (write(s->fd, s->contents, s->len) != s->len)
302 err(1, "Failed to restore %zu bytes", (size_t)s->len);
303 if (ftruncate(s->fd, s->len) != 0)
304 err(1, "Failed to trim file to length %zu",
307 lseek(s->fd, s->off, SEEK_SET);
313 static void free_files(struct saved_file *s)
316 struct saved_file *next = s->next;
323 /* Free up memory, so valgrind doesn't report leaks. */
324 static void free_everything(void)
328 /* We don't do this in cleanup: needed even for failed opens. */
329 for (i = 0; i < history_num; i++) {
330 if (history[i].type == FAILTEST_OPEN)
331 free((char *)history[i].u.open.pathname);
336 static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
340 /* For children, we don't care if they "failed" the testing. */
341 if (control_fd != -1)
347 /* Cleanup everything, in reverse order. */
348 for (i = history_num - 1; i >= 0; i--) {
349 if (!history[i].cleanup)
351 if (!forced_cleanup) {
352 printf("Leak at %s:%u: --failpath=%s\n",
353 history[i].file, history[i].line,
357 history[i].cleanup(&history[i].u);
361 tell_parent(SUCCESS);
365 static bool should_fail(struct failtest_call *call)
368 int control[2], output[2];
369 enum info_type type = UNEXPECTED;
372 struct saved_file *files;
374 /* Are we probing? */
375 if (probe_count && --probe_count == 0 && control_fd != -1)
376 failtest_cleanup(true, 0);
378 if (call == &unrecorded_call)
382 /* + means continue after end, like normal. */
383 if (*failpath == '+')
385 else if (*failpath == '\0') {
386 /* Continue, but don't inject errors. */
387 return call->fail = false;
389 if (tolower((unsigned char)*failpath)
390 != info_to_arg[call->type])
391 errx(1, "Failpath expected '%c' got '%c'\n",
392 info_to_arg[call->type], *failpath);
393 call->fail = isupper((unsigned char)*(failpath++));
398 /* Attach debugger if they asked for it. */
399 if (debugpath && history_num == strlen(debugpath)) {
402 for (i = 0; i < history_num; i++) {
403 unsigned char c = info_to_arg[history[i].type];
406 if (c != debugpath[i])
409 if (i == history_num) {
413 signal(SIGUSR1, SIG_IGN);
414 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
416 if (system(str) == 0)
422 switch (failtest_hook(history, history_num)) {
426 /* Already down probe path? Stop now. */
428 /* FIXME: We should run *parent* and
429 * run probe until calls match up again. */
433 /* Child should give up now. */
434 if (control_fd != -1)
435 failtest_cleanup(true, 0);
436 /* Parent, don't fail again. */
446 files = save_files();
448 /* We're going to fail in the child. */
450 if (pipe(control) != 0 || pipe(output) != 0)
451 err(1, "opening pipe");
453 /* Prevent double-printing (in child and parent) */
457 err(1, "forking failed");
464 diff = time_sub(time_now(), start);
465 p = failpath_string();
466 trace("%u->%u (%u.%02u): %s (", getppid(), getpid(),
467 (int)diff.tv_sec, (int)diff.tv_usec / 10000, p);
469 p = strrchr(history[history_num-1].file, '/');
473 trace("%s", history[history_num-1].file);
474 trace(":%u)\n", history[history_num-1].line);
478 dup2(output[1], STDOUT_FILENO);
479 dup2(output[1], STDERR_FILENO);
480 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
482 control_fd = control[1];
483 /* Valgrind spots the leak if we don't free these. */
488 signal(SIGUSR1, hand_down);
493 /* We grab output so we can display it; we grab writes so we
496 struct pollfd pfd[2];
499 pfd[0].fd = output[0];
500 pfd[0].events = POLLIN|POLLHUP;
501 pfd[1].fd = control[0];
502 pfd[1].events = POLLIN|POLLHUP;
505 ret = poll(pfd, 1, failtest_timeout_ms);
507 ret = poll(pfd, 2, failtest_timeout_ms);
514 err(1, "Poll returned %i", ret);
517 if (pfd[0].revents & POLLIN) {
520 out = realloc(out, outlen + 8192);
521 len = read(output[0], out + outlen, 8192);
523 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
524 if (read_all(control[0], &type, sizeof(type))) {
526 if (!read_write_info(control[0]))
528 } else if (type == RELEASE_LOCKS) {
530 /* FIXME: Tell them we're done... */
533 } else if (pfd[0].revents & POLLHUP) {
536 } while (type != FAILURE);
540 waitpid(child, &status, 0);
541 if (!WIFEXITED(status)) {
542 if (WTERMSIG(status) == SIGUSR1)
543 child_fail(out, outlen, "Timed out");
545 child_fail(out, outlen, "Killed by signal %u: ",
548 /* Child printed failure already, just pass up exit code. */
549 if (type == FAILURE) {
550 fprintf(stderr, "%.*s", (int)outlen, out);
552 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
554 if (WEXITSTATUS(status) != 0)
555 child_fail(out, outlen, "Exited with status %i: ",
556 WEXITSTATUS(status));
559 signal(SIGUSR1, SIG_DFL);
561 restore_files(files);
563 /* We continue onwards without failing. */
568 static void cleanup_calloc(struct calloc_call *call)
573 void *failtest_calloc(size_t nmemb, size_t size,
574 const char *file, unsigned line)
576 struct failtest_call *p;
577 struct calloc_call call;
580 p = add_history(FAILTEST_CALLOC, file, line, &call);
582 if (should_fail(p)) {
583 p->u.calloc.ret = NULL;
586 p->u.calloc.ret = calloc(nmemb, size);
587 set_cleanup(p, cleanup_calloc, struct calloc_call);
590 return p->u.calloc.ret;
593 static void cleanup_malloc(struct malloc_call *call)
598 void *failtest_malloc(size_t size, const char *file, unsigned line)
600 struct failtest_call *p;
601 struct malloc_call call;
604 p = add_history(FAILTEST_MALLOC, file, line, &call);
605 if (should_fail(p)) {
606 p->u.calloc.ret = NULL;
609 p->u.calloc.ret = malloc(size);
610 set_cleanup(p, cleanup_malloc, struct malloc_call);
613 return p->u.calloc.ret;
616 static void cleanup_realloc(struct realloc_call *call)
621 /* Walk back and find out if we got this ptr from a previous routine. */
622 static void fixup_ptr_history(void *ptr, unsigned int last)
626 /* Start at end of history, work back. */
627 for (i = last - 1; i >= 0; i--) {
628 switch (history[i].type) {
629 case FAILTEST_REALLOC:
630 if (history[i].u.realloc.ret == ptr) {
631 history[i].cleanup = NULL;
635 case FAILTEST_MALLOC:
636 if (history[i].u.malloc.ret == ptr) {
637 history[i].cleanup = NULL;
641 case FAILTEST_CALLOC:
642 if (history[i].u.calloc.ret == ptr) {
643 history[i].cleanup = NULL;
653 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
655 struct failtest_call *p;
656 struct realloc_call call;
658 p = add_history(FAILTEST_REALLOC, file, line, &call);
660 /* FIXME: Try one child moving allocation, one not. */
661 if (should_fail(p)) {
662 p->u.realloc.ret = NULL;
665 fixup_ptr_history(ptr, history_num-1);
666 p->u.realloc.ret = realloc(ptr, size);
667 set_cleanup(p, cleanup_realloc, struct realloc_call);
670 return p->u.realloc.ret;
673 void failtest_free(void *ptr)
675 fixup_ptr_history(ptr, history_num);
679 static void cleanup_open(struct open_call *call)
684 int failtest_open(const char *pathname,
685 const char *file, unsigned line, ...)
687 struct failtest_call *p;
688 struct open_call call;
691 call.pathname = strdup(pathname);
693 call.flags = va_arg(ap, int);
694 if (call.flags & O_CREAT) {
695 call.mode = va_arg(ap, int);
698 p = add_history(FAILTEST_OPEN, file, line, &call);
699 /* Avoid memory leak! */
700 if (p == &unrecorded_call)
701 free((char *)call.pathname);
702 p->u.open.ret = open(pathname, call.flags, call.mode);
704 if (p->u.open.ret == -1) {
707 } else if (should_fail(p)) {
708 close(p->u.open.ret);
710 /* FIXME: Play with error codes? */
713 set_cleanup(p, cleanup_open, struct open_call);
716 return p->u.open.ret;
719 static void cleanup_pipe(struct pipe_call *call)
721 if (!call->closed[0])
723 if (!call->closed[1])
727 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
729 struct failtest_call *p;
730 struct pipe_call call;
732 p = add_history(FAILTEST_PIPE, file, line, &call);
733 if (should_fail(p)) {
735 /* FIXME: Play with error codes? */
738 p->u.pipe.ret = pipe(p->u.pipe.fds);
739 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
740 set_cleanup(p, cleanup_pipe, struct pipe_call);
742 /* This causes valgrind to notice if they use pipefd[] after failure */
743 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
745 return p->u.pipe.ret;
748 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
749 const char *file, unsigned line)
751 struct failtest_call *p;
752 struct read_call call;
757 p = add_history(FAILTEST_READ, file, line, &call);
759 /* FIXME: Try partial read returns. */
760 if (should_fail(p)) {
764 p->u.read.ret = pread(fd, buf, count, off);
767 return p->u.read.ret;
770 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
771 const char *file, unsigned line)
773 struct failtest_call *p;
774 struct write_call call;
780 p = add_history(FAILTEST_WRITE, file, line, &call);
782 /* If we're a child, we need to make sure we write the same thing
783 * to non-files as the parent does, so tell it. */
784 if (control_fd != -1 && off == (off_t)-1) {
785 enum info_type type = WRITE;
787 write_all(control_fd, &type, sizeof(type));
788 write_all(control_fd, &p->u.write, sizeof(p->u.write));
789 write_all(control_fd, buf, count);
792 /* FIXME: Try partial write returns. */
793 if (should_fail(p)) {
797 /* FIXME: We assume same write order in parent and child */
798 if (off == (off_t)-1 && child_writes_num != 0) {
799 if (child_writes[0].fd != fd)
800 errx(1, "Child wrote to fd %u, not %u?",
801 child_writes[0].fd, fd);
802 if (child_writes[0].off != p->u.write.off)
803 errx(1, "Child wrote to offset %zu, not %zu?",
804 (size_t)child_writes[0].off,
805 (size_t)p->u.write.off);
806 if (child_writes[0].count != count)
807 errx(1, "Child wrote length %zu, not %zu?",
808 child_writes[0].count, count);
809 if (memcmp(child_writes[0].buf, buf, count)) {
811 "Child wrote differently to"
812 " fd %u than we did!\n", fd);
814 free((char *)child_writes[0].buf);
816 memmove(&child_writes[0], &child_writes[1],
817 sizeof(child_writes[0]) * child_writes_num);
819 /* Is this is a socket or pipe, child wrote it
821 if (p->u.write.off == (off_t)-1) {
822 p->u.write.ret = count;
824 return p->u.write.ret;
827 p->u.write.ret = pwrite(fd, buf, count, off);
830 return p->u.write.ret;
833 ssize_t failtest_read(int fd, void *buf, size_t count,
834 const char *file, unsigned line)
836 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
840 ssize_t failtest_write(int fd, const void *buf, size_t count,
841 const char *file, unsigned line)
843 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
847 static struct lock_info *WARN_UNUSED_RESULT
848 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
853 for (i = 0; i < lock_num; i++) {
858 /* Four cases we care about:
872 if (start > l->start && end < l->end) {
873 /* Mid overlap: trim entry, add new one. */
874 off_t new_start, new_end;
878 locks = add_lock(locks,
879 fd, new_start, new_end, l->type);
881 } else if (start <= l->start && end >= l->end) {
882 /* Total overlap: eliminate entry. */
885 } else if (end >= l->start && end < l->end) {
886 /* Start overlap: trim entry. */
888 } else if (start > l->start && start <= l->end) {
889 /* End overlap: trim entry. */
892 /* Nothing left? Remove it. */
893 if (l->end < l->start) {
894 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
899 if (type != F_UNLCK) {
900 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
901 l = &locks[lock_num++];
910 /* We trap this so we can record it: we don't fail it. */
911 int failtest_close(int fd, const char *file, unsigned line)
914 struct close_call call;
915 struct failtest_call *p;
918 p = add_history(FAILTEST_CLOSE, file, line, &call);
921 /* Consume close from failpath. */
929 /* Trace history to find source of fd. */
930 for (i = history_num-1; i >= 0; i--) {
931 switch (history[i].type) {
934 if (history[i].u.pipe.fds[0] == fd) {
935 assert(!history[i].u.pipe.closed[0]);
936 history[i].u.pipe.closed[0] = true;
937 if (history[i].u.pipe.closed[1])
938 history[i].cleanup = NULL;
941 if (history[i].u.pipe.fds[1] == fd) {
942 assert(!history[i].u.pipe.closed[1]);
943 history[i].u.pipe.closed[1] = true;
944 if (history[i].u.pipe.closed[0])
945 history[i].cleanup = NULL;
950 if (history[i].u.open.ret == fd) {
951 assert((void *)history[i].cleanup
952 == (void *)cleanup_open);
953 history[i].cleanup = NULL;
963 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
967 /* Zero length means "to end of file" */
968 static off_t end_of(off_t start, off_t len)
972 return start + len - 1;
975 /* FIXME: This only handles locks, really. */
976 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
978 struct failtest_call *p;
979 struct fcntl_call call;
985 /* Argument extraction. */
990 call.arg.l = va_arg(ap, long);
992 return fcntl(fd, cmd, call.arg.l);
995 return fcntl(fd, cmd);
999 call.arg.fl = *va_arg(ap, struct flock *);
1001 return fcntl(fd, cmd, &call.arg.fl);
1005 call.arg.fl = *va_arg(ap, struct flock *);
1009 /* This means you need to implement it here. */
1010 err(1, "failtest: unknown fcntl %u", cmd);
1013 p = add_history(FAILTEST_FCNTL, file, line, &call);
1015 if (should_fail(p)) {
1016 p->u.fcntl.ret = -1;
1017 if (p->u.fcntl.cmd == F_SETLK)
1023 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
1024 &p->u.fcntl.arg.fl);
1025 if (p->u.fcntl.ret == -1)
1028 /* We don't handle anything else yet. */
1029 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1030 locks = add_lock(locks,
1032 p->u.fcntl.arg.fl.l_start,
1033 end_of(p->u.fcntl.arg.fl.l_start,
1034 p->u.fcntl.arg.fl.l_len),
1035 p->u.fcntl.arg.fl.l_type);
1039 return p->u.fcntl.ret;
1042 pid_t failtest_getpid(const char *file, unsigned line)
1044 /* You must call failtest_init first! */
1049 void failtest_init(int argc, char *argv[])
1053 orig_pid = getpid();
1055 for (i = 1; i < argc; i++) {
1056 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1057 failpath = argv[i] + strlen("--failpath=");
1058 } else if (strcmp(argv[i], "--tracepath") == 0) {
1059 tracefd = dup(STDERR_FILENO);
1060 failtest_timeout_ms = -1;
1061 } else if (!strncmp(argv[i], "--debugpath=",
1062 strlen("--debugpath="))) {
1063 debugpath = argv[i] + strlen("--debugpath=");
1069 bool failtest_has_failed(void)
1071 return control_fd != -1;
1074 void failtest_exit(int status)
1076 if (failtest_exit_check) {
1077 if (!failtest_exit_check(history, history_num))
1078 child_fail(NULL, 0, "failtest_exit_check failed\n");
1081 failtest_cleanup(false, status);