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>
22 #include <ccan/str/str.h>
24 enum failtest_result (*failtest_hook)(struct tlist_calls *);
26 static int tracefd = -1;
28 unsigned int failtest_timeout_ms = 20000;
31 const char *debugpath;
43 /* end is inclusive: you can't have a 0-byte lock. */
48 bool (*failtest_exit_check)(struct tlist_calls *history);
50 static struct tlist_calls history = TLIST_INIT(history);
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 struct failtest_call *call;
77 /* NULL file is how we suppress failure. */
79 return &unrecorded_call;
81 call = malloc(sizeof *call);
86 memcpy(&call->u, elem, elem_size);
87 tlist_add_tail(&history, call, list);
91 #define add_history(type, file, line, elem) \
92 add_history_((type), (file), (line), (elem), sizeof(*(elem)))
94 /* We do a fake call inside a sizeof(), to check types. */
95 #define set_cleanup(call, clean, type) \
96 (call)->cleanup = (void *)((void)sizeof(clean((type *)NULL),1), (clean))
99 /* Dup the fd to a high value (out of the way I hope!), and close the old fd. */
100 static int move_fd_to_high(int fd)
104 for (i = FD_SETSIZE - 1; i >= 0; i--) {
105 if (fcntl(i, F_GETFL) == -1 && errno == EBADF) {
106 if (dup2(fd, i) == -1)
107 err(1, "Failed to dup fd %i to %i", fd, i);
112 /* Nothing? Really? Er... ok? */
116 static bool read_write_info(int fd)
118 struct write_call *w;
121 /* We don't need all of this, but it's simple. */
122 child_writes = realloc(child_writes,
123 (child_writes_num+1) * sizeof(child_writes[0]));
124 w = &child_writes[child_writes_num];
125 if (!read_all(fd, w, sizeof(*w)))
128 w->buf = buf = malloc(w->count);
129 if (!read_all(fd, buf, w->count))
136 static char *failpath_string(void)
138 struct failtest_call *i;
139 char *ret = strdup("");
142 /* Inefficient, but who cares? */
143 tlist_for_each(&history, i, list) {
144 ret = realloc(ret, len + 2);
145 ret[len] = info_to_arg[i->type];
147 ret[len] = toupper(ret[len]);
153 static void tell_parent(enum info_type type)
155 if (control_fd != -1)
156 write_all(control_fd, &type, sizeof(type));
159 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
162 char *path = failpath_string();
165 vfprintf(stderr, fmt, ap);
168 fprintf(stderr, "%.*s", (int)outlen, out);
169 printf("To reproduce: --failpath=%s\n", path);
171 tell_parent(FAILURE);
175 static void trace(const char *fmt, ...)
183 vdprintf(tracefd, fmt, ap);
189 static void hand_down(int signum)
194 static void release_locks(void)
196 /* Locks were never acquired/reacquired? */
200 /* We own them? Release them all. */
201 if (lock_owner == getpid()) {
205 fl.l_whence = SEEK_SET;
209 for (i = 0; i < lock_num; i++)
210 fcntl(locks[i].fd, F_SETLK, &fl);
212 /* Our parent must have them; pass request up. */
213 enum info_type type = RELEASE_LOCKS;
214 assert(control_fd != -1);
215 write_all(control_fd, &type, sizeof(type));
220 /* off_t is a signed type. Getting its max is non-trivial. */
221 static off_t off_max(void)
223 BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
224 if (sizeof(off_t) == 4)
225 return (off_t)0x7FFFFFF;
227 return (off_t)0x7FFFFFFFFFFFFFFULL;
230 static void get_locks(void)
235 if (lock_owner == getpid())
238 if (lock_owner != 0) {
239 enum info_type type = RELEASE_LOCKS;
240 assert(control_fd != -1);
241 write_all(control_fd, &type, sizeof(type));
244 fl.l_whence = SEEK_SET;
246 for (i = 0; i < lock_num; i++) {
247 fl.l_type = locks[i].type;
248 fl.l_start = locks[i].start;
249 if (locks[i].end == off_max())
252 fl.l_len = locks[i].end - locks[i].start + 1;
254 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
257 lock_owner = getpid();
261 struct saved_file *next;
267 static struct saved_file *save_file(struct saved_file *next, int fd)
269 struct saved_file *s = malloc(sizeof(*s));
273 s->off = lseek(fd, 0, SEEK_CUR);
274 /* Special file? Erk... */
275 assert(s->off != -1);
276 s->len = lseek(fd, 0, SEEK_END);
277 lseek(fd, 0, SEEK_SET);
278 s->contents = malloc(s->len);
279 if (read(fd, s->contents, s->len) != s->len)
280 err(1, "Failed to save %zu bytes", (size_t)s->len);
281 lseek(fd, s->off, SEEK_SET);
285 /* We have little choice but to save and restore open files: mmap means we
286 * can really intercept changes in the child.
288 * We could do non-mmap'ed files on demand, however. */
289 static struct saved_file *save_files(void)
291 struct saved_file *files = NULL;
292 struct failtest_call *i;
294 /* Figure out the set of live fds. */
295 tlist_for_each_rev(&history, i, list) {
296 if (i->type == FAILTEST_OPEN) {
297 int fd = i->u.open.ret;
298 /* Only do successful, writable fds. */
302 /* If it was closed, cleanup == NULL. */
306 if ((i->u.open.flags & O_RDWR) == O_RDWR) {
307 files = save_file(files, fd);
308 } else if ((i->u.open.flags & O_WRONLY)
310 /* FIXME: Handle O_WRONLY. Open with O_RDWR? */
319 static void restore_files(struct saved_file *s)
322 struct saved_file *next = s->next;
324 lseek(s->fd, 0, SEEK_SET);
325 if (write(s->fd, s->contents, s->len) != s->len)
326 err(1, "Failed to restore %zu bytes", (size_t)s->len);
327 if (ftruncate(s->fd, s->len) != 0)
328 err(1, "Failed to trim file to length %zu",
331 lseek(s->fd, s->off, SEEK_SET);
337 static void free_files(struct saved_file *s)
340 struct saved_file *next = s->next;
347 static void free_call(struct failtest_call *call)
349 /* We don't do this in cleanup: needed even for failed opens. */
350 if (call->type == FAILTEST_OPEN)
351 free((char *)call->u.open.pathname);
352 tlist_del_from(&history, call, list);
356 /* Free up memory, so valgrind doesn't report leaks. */
357 static void free_everything(void)
359 struct failtest_call *i;
361 while ((i = tlist_top(&history, struct failtest_call, list)) != NULL)
365 static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
367 struct failtest_call *i;
369 /* For children, we don't care if they "failed" the testing. */
370 if (control_fd != -1)
373 if (forced_cleanup) {
374 /* We didn't actually do final operation: remove it. */
375 i = tlist_tail(&history, struct failtest_call, list);
379 /* Cleanup everything, in reverse order. */
380 tlist_for_each_rev(&history, i, list) {
383 if (!forced_cleanup) {
384 printf("Leak at %s:%u: --failpath=%s\n",
385 i->file, i->line, failpath_string());
392 tell_parent(SUCCESS);
396 static bool should_fail(struct failtest_call *call)
399 int control[2], output[2];
400 enum info_type type = UNEXPECTED;
403 struct saved_file *files;
405 /* Are we probing? */
406 if (probe_count && --probe_count == 0 && control_fd != -1)
407 failtest_cleanup(true, 0);
409 if (call == &unrecorded_call)
413 /* + means continue after end, like normal. */
414 if (*failpath == '+')
416 else if (*failpath == '\0') {
417 /* Continue, but don't inject errors. */
418 return call->fail = false;
420 if (tolower((unsigned char)*failpath)
421 != info_to_arg[call->type])
422 errx(1, "Failpath expected '%c' got '%c'\n",
423 info_to_arg[call->type], *failpath);
424 call->fail = cisupper(*(failpath++));
429 /* Attach debugger if they asked for it. */
431 char *path = failpath_string();
433 if (streq(path, debugpath)) {
437 signal(SIGUSR1, SIG_IGN);
438 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
440 if (system(str) == 0)
442 } else if (!strstarts(path, debugpath)) {
443 fprintf(stderr, "--debugpath not followed: %s\n", path);
450 switch (failtest_hook(&history)) {
454 /* Already down probe path? Stop now. */
456 /* FIXME: We should run *parent* and
457 * run probe until calls match up again. */
461 /* Child should give up now. */
462 if (control_fd != -1)
463 failtest_cleanup(true, 0);
464 /* Parent, don't fail again. */
474 files = save_files();
476 /* We're going to fail in the child. */
478 if (pipe(control) != 0 || pipe(output) != 0)
479 err(1, "opening pipe");
481 /* Prevent double-printing (in child and parent) */
485 err(1, "forking failed");
492 struct failtest_call *c;
494 c = tlist_tail(&history, struct failtest_call, list);
495 diff = time_sub(time_now(), start);
496 failpath = failpath_string();
497 trace("%u->%u (%u.%02u): %s (", getppid(), getpid(),
498 (int)diff.tv_sec, (int)diff.tv_usec / 10000,
501 p = strrchr(c->file, '/');
505 trace("%s", c->file);
506 trace(":%u)\n", c->line);
510 dup2(output[1], STDOUT_FILENO);
511 dup2(output[1], STDERR_FILENO);
512 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
514 control_fd = move_fd_to_high(control[1]);
515 /* Valgrind spots the leak if we don't free these. */
520 signal(SIGUSR1, hand_down);
525 /* We grab output so we can display it; we grab writes so we
528 struct pollfd pfd[2];
531 pfd[0].fd = output[0];
532 pfd[0].events = POLLIN|POLLHUP;
533 pfd[1].fd = control[0];
534 pfd[1].events = POLLIN|POLLHUP;
537 ret = poll(pfd, 1, failtest_timeout_ms);
539 ret = poll(pfd, 2, failtest_timeout_ms);
546 err(1, "Poll returned %i", ret);
549 if (pfd[0].revents & POLLIN) {
552 out = realloc(out, outlen + 8192);
553 len = read(output[0], out + outlen, 8192);
555 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
556 if (read_all(control[0], &type, sizeof(type))) {
558 if (!read_write_info(control[0]))
560 } else if (type == RELEASE_LOCKS) {
562 /* FIXME: Tell them we're done... */
565 } else if (pfd[0].revents & POLLHUP) {
568 } while (type != FAILURE);
572 waitpid(child, &status, 0);
573 if (!WIFEXITED(status)) {
574 if (WTERMSIG(status) == SIGUSR1)
575 child_fail(out, outlen, "Timed out");
577 child_fail(out, outlen, "Killed by signal %u: ",
580 /* Child printed failure already, just pass up exit code. */
581 if (type == FAILURE) {
582 fprintf(stderr, "%.*s", (int)outlen, out);
584 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
586 if (WEXITSTATUS(status) != 0)
587 child_fail(out, outlen, "Exited with status %i: ",
588 WEXITSTATUS(status));
591 signal(SIGUSR1, SIG_DFL);
593 restore_files(files);
595 /* We continue onwards without failing. */
600 static void cleanup_calloc(struct calloc_call *call)
605 void *failtest_calloc(size_t nmemb, size_t size,
606 const char *file, unsigned line)
608 struct failtest_call *p;
609 struct calloc_call call;
612 p = add_history(FAILTEST_CALLOC, file, line, &call);
614 if (should_fail(p)) {
615 p->u.calloc.ret = NULL;
618 p->u.calloc.ret = calloc(nmemb, size);
619 set_cleanup(p, cleanup_calloc, struct calloc_call);
622 return p->u.calloc.ret;
625 static void cleanup_malloc(struct malloc_call *call)
630 void *failtest_malloc(size_t size, const char *file, unsigned line)
632 struct failtest_call *p;
633 struct malloc_call call;
636 p = add_history(FAILTEST_MALLOC, file, line, &call);
637 if (should_fail(p)) {
638 p->u.malloc.ret = NULL;
641 p->u.malloc.ret = malloc(size);
642 set_cleanup(p, cleanup_malloc, struct malloc_call);
645 return p->u.malloc.ret;
648 static void cleanup_realloc(struct realloc_call *call)
653 /* Walk back and find out if we got this ptr from a previous routine. */
654 static void fixup_ptr_history(void *ptr)
656 struct failtest_call *i;
658 /* Start at end of history, work back. */
659 tlist_for_each_rev(&history, i, list) {
661 case FAILTEST_REALLOC:
662 if (i->u.realloc.ret == ptr) {
667 case FAILTEST_MALLOC:
668 if (i->u.malloc.ret == ptr) {
673 case FAILTEST_CALLOC:
674 if (i->u.calloc.ret == ptr) {
685 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
687 struct failtest_call *p;
688 struct realloc_call call;
690 p = add_history(FAILTEST_REALLOC, file, line, &call);
692 /* FIXME: Try one child moving allocation, one not. */
693 if (should_fail(p)) {
694 p->u.realloc.ret = NULL;
697 /* Don't catch this one in the history fixup... */
698 p->u.realloc.ret = NULL;
699 fixup_ptr_history(ptr);
700 p->u.realloc.ret = realloc(ptr, size);
701 set_cleanup(p, cleanup_realloc, struct realloc_call);
704 return p->u.realloc.ret;
707 void failtest_free(void *ptr)
709 fixup_ptr_history(ptr);
713 static void cleanup_open(struct open_call *call)
718 int failtest_open(const char *pathname,
719 const char *file, unsigned line, ...)
721 struct failtest_call *p;
722 struct open_call call;
725 call.pathname = strdup(pathname);
727 call.flags = va_arg(ap, int);
728 if (call.flags & O_CREAT) {
729 call.mode = va_arg(ap, int);
732 p = add_history(FAILTEST_OPEN, file, line, &call);
733 /* Avoid memory leak! */
734 if (p == &unrecorded_call)
735 free((char *)call.pathname);
736 p->u.open.ret = open(pathname, call.flags, call.mode);
738 if (p->u.open.ret == -1) {
741 } else if (should_fail(p)) {
742 close(p->u.open.ret);
744 /* FIXME: Play with error codes? */
747 set_cleanup(p, cleanup_open, struct open_call);
750 return p->u.open.ret;
753 static void cleanup_pipe(struct pipe_call *call)
755 if (!call->closed[0])
757 if (!call->closed[1])
761 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
763 struct failtest_call *p;
764 struct pipe_call call;
766 p = add_history(FAILTEST_PIPE, file, line, &call);
767 if (should_fail(p)) {
769 /* FIXME: Play with error codes? */
772 p->u.pipe.ret = pipe(p->u.pipe.fds);
773 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
774 set_cleanup(p, cleanup_pipe, struct pipe_call);
776 /* This causes valgrind to notice if they use pipefd[] after failure */
777 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
779 return p->u.pipe.ret;
782 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
783 const char *file, unsigned line)
785 struct failtest_call *p;
786 struct read_call call;
791 p = add_history(FAILTEST_READ, file, line, &call);
793 /* FIXME: Try partial read returns. */
794 if (should_fail(p)) {
798 p->u.read.ret = pread(fd, buf, count, off);
801 return p->u.read.ret;
804 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
805 const char *file, unsigned line)
807 struct failtest_call *p;
808 struct write_call call;
814 p = add_history(FAILTEST_WRITE, file, line, &call);
816 /* If we're a child, we need to make sure we write the same thing
817 * to non-files as the parent does, so tell it. */
818 if (control_fd != -1 && off == (off_t)-1) {
819 enum info_type type = WRITE;
821 write_all(control_fd, &type, sizeof(type));
822 write_all(control_fd, &p->u.write, sizeof(p->u.write));
823 write_all(control_fd, buf, count);
826 /* FIXME: Try partial write returns. */
827 if (should_fail(p)) {
831 /* FIXME: We assume same write order in parent and child */
832 if (off == (off_t)-1 && child_writes_num != 0) {
833 if (child_writes[0].fd != fd)
834 errx(1, "Child wrote to fd %u, not %u?",
835 child_writes[0].fd, fd);
836 if (child_writes[0].off != p->u.write.off)
837 errx(1, "Child wrote to offset %zu, not %zu?",
838 (size_t)child_writes[0].off,
839 (size_t)p->u.write.off);
840 if (child_writes[0].count != count)
841 errx(1, "Child wrote length %zu, not %zu?",
842 child_writes[0].count, count);
843 if (memcmp(child_writes[0].buf, buf, count)) {
845 "Child wrote differently to"
846 " fd %u than we did!\n", fd);
848 free((char *)child_writes[0].buf);
850 memmove(&child_writes[0], &child_writes[1],
851 sizeof(child_writes[0]) * child_writes_num);
853 /* Is this is a socket or pipe, child wrote it
855 if (p->u.write.off == (off_t)-1) {
856 p->u.write.ret = count;
858 return p->u.write.ret;
861 p->u.write.ret = pwrite(fd, buf, count, off);
864 return p->u.write.ret;
867 ssize_t failtest_read(int fd, void *buf, size_t count,
868 const char *file, unsigned line)
870 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
874 ssize_t failtest_write(int fd, const void *buf, size_t count,
875 const char *file, unsigned line)
877 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
881 static struct lock_info *WARN_UNUSED_RESULT
882 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
887 for (i = 0; i < lock_num; i++) {
892 /* Four cases we care about:
906 if (start > l->start && end < l->end) {
907 /* Mid overlap: trim entry, add new one. */
908 off_t new_start, new_end;
912 locks = add_lock(locks,
913 fd, new_start, new_end, l->type);
915 } else if (start <= l->start && end >= l->end) {
916 /* Total overlap: eliminate entry. */
919 } else if (end >= l->start && end < l->end) {
920 /* Start overlap: trim entry. */
922 } else if (start > l->start && start <= l->end) {
923 /* End overlap: trim entry. */
926 /* Nothing left? Remove it. */
927 if (l->end < l->start) {
928 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
933 if (type != F_UNLCK) {
934 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
935 l = &locks[lock_num++];
944 /* We trap this so we can record it: we don't fail it. */
945 int failtest_close(int fd, const char *file, unsigned line)
947 struct failtest_call *i;
948 struct close_call call;
949 struct failtest_call *p;
952 p = add_history(FAILTEST_CLOSE, file, line, &call);
955 /* Consume close from failpath. */
963 /* Trace history to find source of fd. */
964 tlist_for_each_rev(&history, i, list) {
968 if (i->u.pipe.fds[0] == fd) {
969 assert(!i->u.pipe.closed[0]);
970 i->u.pipe.closed[0] = true;
971 if (i->u.pipe.closed[1])
975 if (i->u.pipe.fds[1] == fd) {
976 assert(!i->u.pipe.closed[1]);
977 i->u.pipe.closed[1] = true;
978 if (i->u.pipe.closed[0])
984 if (i->u.open.ret == fd) {
985 assert((void *)i->cleanup
986 == (void *)cleanup_open);
997 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
1001 /* Zero length means "to end of file" */
1002 static off_t end_of(off_t start, off_t len)
1006 return start + len - 1;
1009 /* FIXME: This only handles locks, really. */
1010 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
1012 struct failtest_call *p;
1013 struct fcntl_call call;
1019 /* Argument extraction. */
1024 call.arg.l = va_arg(ap, long);
1026 return fcntl(fd, cmd, call.arg.l);
1029 return fcntl(fd, cmd);
1033 call.arg.fl = *va_arg(ap, struct flock *);
1035 return fcntl(fd, cmd, &call.arg.fl);
1039 call.arg.fl = *va_arg(ap, struct flock *);
1043 /* This means you need to implement it here. */
1044 err(1, "failtest: unknown fcntl %u", cmd);
1047 p = add_history(FAILTEST_FCNTL, file, line, &call);
1049 if (should_fail(p)) {
1050 p->u.fcntl.ret = -1;
1051 if (p->u.fcntl.cmd == F_SETLK)
1057 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
1058 &p->u.fcntl.arg.fl);
1059 if (p->u.fcntl.ret == -1)
1062 /* We don't handle anything else yet. */
1063 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1064 locks = add_lock(locks,
1066 p->u.fcntl.arg.fl.l_start,
1067 end_of(p->u.fcntl.arg.fl.l_start,
1068 p->u.fcntl.arg.fl.l_len),
1069 p->u.fcntl.arg.fl.l_type);
1073 return p->u.fcntl.ret;
1076 pid_t failtest_getpid(const char *file, unsigned line)
1078 /* You must call failtest_init first! */
1083 void failtest_init(int argc, char *argv[])
1087 orig_pid = getpid();
1089 for (i = 1; i < argc; i++) {
1090 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1091 failpath = argv[i] + strlen("--failpath=");
1092 } else if (strcmp(argv[i], "--tracepath") == 0) {
1093 tracefd = move_fd_to_high(STDERR_FILENO);
1094 failtest_timeout_ms = -1;
1095 } else if (!strncmp(argv[i], "--debugpath=",
1096 strlen("--debugpath="))) {
1097 debugpath = argv[i] + strlen("--debugpath=");
1103 bool failtest_has_failed(void)
1105 return control_fd != -1;
1108 void failtest_exit(int status)
1110 if (failtest_exit_check) {
1111 if (!failtest_exit_check(&history))
1112 child_fail(NULL, 0, "failtest_exit_check failed\n");
1115 failtest_cleanup(false, status);