1 /* Licensed under LGPL - see LICENSE file for details */
2 #include <ccan/failtest/failtest.h>
12 #include <sys/types.h>
19 #include <ccan/time/time.h>
20 #include <ccan/read_write_all/read_write_all.h>
21 #include <ccan/failtest/failtest_proto.h>
22 #include <ccan/build_assert/build_assert.h>
23 #include <ccan/hash/hash.h>
24 #include <ccan/htable/htable_type.h>
25 #include <ccan/str/str.h>
26 #include <ccan/compiler/compiler.h>
28 enum failtest_result (*failtest_hook)(struct tlist_calls *);
30 static FILE *tracef = NULL, *warnf;
31 static int traceindent = 0;
33 unsigned int failtest_timeout_ms = 20000;
36 const char *debugpath;
48 /* end is inclusive: you can't have a 0-byte lock. */
53 /* We hash the call location together with its backtrace. */
54 static size_t hash_call(const struct failtest_call *call)
56 return hash(call->file, strlen(call->file),
58 hash(call->backtrace, call->backtrace_num,
62 static bool call_eq(const struct failtest_call *call1,
63 const struct failtest_call *call2)
67 if (strcmp(call1->file, call2->file) != 0
68 || call1->line != call2->line
69 || call1->type != call2->type
70 || call1->backtrace_num != call2->backtrace_num)
73 for (i = 0; i < call1->backtrace_num; i++)
74 if (call1->backtrace[i] != call2->backtrace[i])
80 /* Defines struct failtable. */
81 HTABLE_DEFINE_TYPE(struct failtest_call, (struct failtest_call *), hash_call,
84 bool (*failtest_exit_check)(struct tlist_calls *history);
86 /* The entire history of all calls. */
87 static struct tlist_calls history = TLIST_INIT(history);
88 /* If we're a child, the fd two write control info to the parent. */
89 static int control_fd = -1;
90 /* If we're a child, this is the first call we did ourselves. */
91 static struct failtest_call *our_history_start = NULL;
92 /* For printing runtime with --trace. */
93 static struct timeval start;
94 /* Set when failtest_hook returns FAIL_PROBE */
95 static bool probing = false;
96 /* Table to track duplicates. */
97 static struct failtable failtable;
99 /* Array of writes which our child did. We report them on failure. */
100 static struct write_call *child_writes = NULL;
101 static unsigned int child_writes_num = 0;
103 /* fcntl locking info. */
104 static pid_t lock_owner;
105 static struct lock_info *locks = NULL;
106 static unsigned int lock_num = 0;
108 /* Our original pid, which we return to anyone who asks. */
109 static pid_t orig_pid;
111 /* Mapping from failtest_type to char. */
112 static const char info_to_arg[] = "mceoxprwfal";
114 /* Dummy call used for failtest_undo wrappers. */
115 static struct failtest_call unrecorded_call;
117 struct contents_saved {
124 /* File contents, saved in this child only. */
125 struct saved_mmapped_file {
126 struct saved_mmapped_file *next;
127 struct failtest_call *opener;
128 struct contents_saved *s;
131 static struct saved_mmapped_file *saved_mmapped_files;
134 #include <execinfo.h>
136 static void **get_backtrace(unsigned int *num)
138 static unsigned int max_back = 100;
142 ret = malloc(max_back * sizeof(void *));
143 *num = backtrace(ret, max_back);
144 if (*num == max_back) {
152 /* This will test slightly less, since will consider all of the same
153 * calls as identical. But, it's slightly faster! */
154 static void **get_backtrace(unsigned int *num)
159 #endif /* HAVE_BACKTRACE */
161 static struct failtest_call *add_history_(enum failtest_call_type type,
168 struct failtest_call *call;
170 /* NULL file is how we suppress failure. */
172 return &unrecorded_call;
174 call = malloc(sizeof *call);
176 call->can_leak = can_leak;
179 call->cleanup = NULL;
180 call->backtrace = get_backtrace(&call->backtrace_num);
181 memcpy(&call->u, elem, elem_size);
182 tlist_add_tail(&history, call, list);
186 #define add_history(type, can_leak, file, line, elem) \
187 add_history_((type), (can_leak), (file), (line), (elem), sizeof(*(elem)))
189 /* We do a fake call inside a sizeof(), to check types. */
190 #define set_cleanup(call, clean, type) \
191 (call)->cleanup = (void *)((void)sizeof(clean((type *)NULL, false),1), (clean))
193 /* Dup the fd to a high value (out of the way I hope!), and close the old fd. */
194 static int move_fd_to_high(int fd)
198 for (i = FD_SETSIZE - 1; i >= 0; i--) {
199 if (fcntl(i, F_GETFL) == -1 && errno == EBADF) {
200 if (dup2(fd, i) == -1)
201 err(1, "Failed to dup fd %i to %i", fd, i);
206 /* Nothing? Really? Er... ok? */
210 static bool read_write_info(int fd)
212 struct write_call *w;
215 /* We don't need all of this, but it's simple. */
216 child_writes = realloc(child_writes,
217 (child_writes_num+1) * sizeof(child_writes[0]));
218 w = &child_writes[child_writes_num];
219 if (!read_all(fd, w, sizeof(*w)))
222 w->buf = buf = malloc(w->count);
223 if (!read_all(fd, buf, w->count))
230 static char *failpath_string(void)
232 struct failtest_call *i;
233 char *ret = strdup("");
236 /* Inefficient, but who cares? */
237 tlist_for_each(&history, i, list) {
238 ret = realloc(ret, len + 2);
239 ret[len] = info_to_arg[i->type];
241 ret[len] = toupper(ret[len]);
247 static void do_warn(int e, const char *fmt, va_list ap)
249 char *p = failpath_string();
251 vfprintf(warnf, fmt, ap);
253 fprintf(warnf, ": %s", strerror(e));
254 fprintf(warnf, " [%s]\n", p);
258 static void fwarn(const char *fmt, ...)
269 static void fwarnx(const char *fmt, ...)
274 do_warn(-1, fmt, ap);
278 static void tell_parent(enum info_type type)
280 if (control_fd != -1)
281 write_all(control_fd, &type, sizeof(type));
284 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
287 char *path = failpath_string();
290 vfprintf(stderr, fmt, ap);
293 fprintf(stderr, "%.*s", (int)outlen, out);
294 printf("To reproduce: --failpath=%s\n", path);
296 tell_parent(FAILURE);
300 static void PRINTF_FMT(1, 2) trace(const char *fmt, ...)
310 for (i = 0; i < traceindent; i++)
311 fprintf(tracef, " ");
313 p = failpath_string();
314 fprintf(tracef, "%i: %u: %s ", idx++, getpid(), p);
316 vfprintf(tracef, fmt, ap);
323 static void hand_down(int signum)
328 static void release_locks(void)
330 /* Locks were never acquired/reacquired? */
334 /* We own them? Release them all. */
335 if (lock_owner == getpid()) {
339 fl.l_whence = SEEK_SET;
343 trace("Releasing %u locks\n", lock_num);
344 for (i = 0; i < lock_num; i++)
345 fcntl(locks[i].fd, F_SETLK, &fl);
347 /* Our parent must have them; pass request up. */
348 enum info_type type = RELEASE_LOCKS;
349 assert(control_fd != -1);
350 write_all(control_fd, &type, sizeof(type));
355 /* off_t is a signed type. Getting its max is non-trivial. */
356 static off_t off_max(void)
358 BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
359 if (sizeof(off_t) == 4)
360 return (off_t)0x7FFFFFF;
362 return (off_t)0x7FFFFFFFFFFFFFFULL;
365 static void get_locks(void)
370 if (lock_owner == getpid())
373 if (lock_owner != 0) {
374 enum info_type type = RELEASE_LOCKS;
375 assert(control_fd != -1);
376 trace("Asking parent to release locks\n");
377 write_all(control_fd, &type, sizeof(type));
380 fl.l_whence = SEEK_SET;
382 for (i = 0; i < lock_num; i++) {
383 fl.l_type = locks[i].type;
384 fl.l_start = locks[i].start;
385 if (locks[i].end == off_max())
388 fl.l_len = locks[i].end - locks[i].start + 1;
390 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
393 trace("Acquired %u locks\n", lock_num);
394 lock_owner = getpid();
398 static struct contents_saved *save_contents(const char *filename,
399 int fd, size_t count, off_t off,
402 struct contents_saved *s = malloc(sizeof(*s) + count);
407 ret = pread(fd, s->contents, count, off);
409 fwarn("failtest_write: failed to save old contents!");
414 /* Use lseek to get the size of file, but we have to restore
416 off = lseek(fd, 0, SEEK_CUR);
417 s->old_len = lseek(fd, 0, SEEK_END);
418 lseek(fd, off, SEEK_SET);
420 trace("Saving %p %s %zu@%llu after %s (filelength %llu) via fd %i\n",
421 s, filename, s->count, (long long)s->off, why,
422 (long long)s->old_len, fd);
426 static void restore_contents(struct failtest_call *opener,
427 struct contents_saved *s,
433 /* The top parent doesn't need to restore. */
434 if (control_fd == -1)
437 /* Has the fd been closed? */
438 if (opener->u.open.closed) {
439 /* Reopen, replace fd, close silently as we clean up. */
440 fd = open(opener->u.open.pathname, O_RDWR);
442 fwarn("failtest: could not reopen %s to clean up %s!",
443 opener->u.open.pathname, caller);
446 /* Make it clearly distinguisable from a "normal" fd. */
447 fd = move_fd_to_high(fd);
448 trace("Reopening %s to restore it (was fd %i, now %i)\n",
449 opener->u.open.pathname, opener->u.open.ret, fd);
450 opener->u.open.ret = fd;
451 opener->u.open.closed = false;
453 fd = opener->u.open.ret;
455 trace("Restoring %p %s %zu@%llu after %s (filelength %llu) via fd %i\n",
456 s, opener->u.open.pathname, s->count, (long long)s->off, caller,
457 (long long)s->old_len, fd);
458 if (pwrite(fd, s->contents, s->count, s->off) != s->count) {
459 fwarn("failtest: write failed cleaning up %s for %s!",
460 opener->u.open.pathname, caller);
463 if (ftruncate(fd, s->old_len) != 0) {
464 fwarn("failtest_write: truncate failed cleaning up %s for %s!",
465 opener->u.open.pathname, caller);
468 if (restore_offset) {
469 trace("Restoring offset of fd %i to %llu\n",
470 fd, (long long)s->off);
471 lseek(fd, s->off, SEEK_SET);
475 /* We save/restore most things on demand, but always do mmaped files. */
476 static void save_mmapped_files(void)
478 struct failtest_call *i;
479 trace("Saving mmapped files in child\n");
481 tlist_for_each_rev(&history, i, list) {
482 struct mmap_call *m = &i->u.mmap;
483 struct saved_mmapped_file *s;
485 if (i->type != FAILTEST_MMAP)
488 /* FIXME: We only handle mmapped files where fd is still open. */
489 if (m->opener->u.open.closed)
492 s = malloc(sizeof *s);
493 s->s = save_contents(m->opener->u.open.pathname,
494 m->fd, m->length, m->offset,
495 "mmapped file before fork");
496 s->opener = m->opener;
497 s->next = saved_mmapped_files;
498 saved_mmapped_files = s;
502 static void free_mmapped_files(bool restore)
504 trace("%s mmapped files in child\n",
505 restore ? "Restoring" : "Discarding");
506 while (saved_mmapped_files) {
507 struct saved_mmapped_file *next = saved_mmapped_files->next;
509 restore_contents(saved_mmapped_files->opener,
510 saved_mmapped_files->s, false,
512 free(saved_mmapped_files->s);
513 free(saved_mmapped_files);
514 saved_mmapped_files = next;
518 /* Returns a FAILTEST_OPEN, FAILTEST_PIPE or NULL. */
519 static struct failtest_call *opener_of(int fd)
521 struct failtest_call *i;
523 /* Don't get confused and match genuinely failed opens. */
527 /* Figure out the set of live fds. */
528 tlist_for_each_rev(&history, i, list) {
533 if (i->u.close.fd == fd) {
538 if (i->u.open.ret == fd) {
539 if (i->u.open.closed)
545 if (i->u.pipe.fds[0] == fd || i->u.pipe.fds[1] == fd) {
554 /* FIXME: socket, dup, etc are untracked! */
558 static void free_call(struct failtest_call *call)
560 /* We don't do this in cleanup: needed even for failed opens. */
561 if (call->type == FAILTEST_OPEN)
562 free((char *)call->u.open.pathname);
563 free(call->backtrace);
564 tlist_del_from(&history, call, list);
568 /* Free up memory, so valgrind doesn't report leaks. */
569 static void free_everything(void)
571 struct failtest_call *i;
573 while ((i = tlist_top(&history, list)) != NULL)
576 failtable_clear(&failtable);
579 static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
581 struct failtest_call *i;
584 /* For children, we don't care if they "failed" the testing. */
585 if (control_fd != -1)
588 /* We don't restore contents for original parent. */
591 /* Cleanup everything, in reverse order. */
592 tlist_for_each_rev(&history, i, list) {
593 /* Don't restore things our parent did. */
594 if (i == our_history_start)
601 i->cleanup(&i->u, restore);
603 /* But their program shouldn't leak, even on failure. */
604 if (!forced_cleanup && i->can_leak) {
605 printf("Leak at %s:%u: --failpath=%s\n",
606 i->file, i->line, failpath_string());
611 /* Put back mmaped files the way our parent (if any) expects. */
612 free_mmapped_files(true);
616 tell_parent(SUCCESS);
618 tell_parent(FAILURE);
622 static bool following_path(void)
626 /* + means continue after end, like normal. */
627 if (*failpath == '+') {
634 static bool follow_path(struct failtest_call *call)
636 if (*failpath == '\0') {
637 /* Continue, but don't inject errors. */
638 return call->fail = false;
641 if (tolower((unsigned char)*failpath) != info_to_arg[call->type])
642 errx(1, "Failpath expected '%s' got '%c'\n",
643 failpath, info_to_arg[call->type]);
644 call->fail = cisupper(*(failpath++));
646 call->can_leak = false;
650 static bool should_fail(struct failtest_call *call)
653 int control[2], output[2];
654 enum info_type type = UNEXPECTED;
657 struct failtest_call *dup;
659 if (call == &unrecorded_call)
662 if (following_path())
663 return follow_path(call);
665 /* Attach debugger if they asked for it. */
669 /* Pretend this last call matches whatever path wanted:
670 * keeps valgrind happy. */
671 call->fail = cisupper(debugpath[strlen(debugpath)-1]);
672 path = failpath_string();
674 if (streq(path, debugpath)) {
678 signal(SIGUSR1, SIG_IGN);
679 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
681 if (system(str) == 0)
684 /* Ignore last character: could be upper or lower. */
685 path[strlen(path)-1] = '\0';
686 if (!strstarts(debugpath, path)) {
688 "--debugpath not followed: %s\n", path);
695 /* Are we probing? If so, we never fail twice. */
697 trace("Not failing %c due to FAIL_PROBE return\n",
698 info_to_arg[call->type]);
699 return call->fail = false;
702 /* Don't fail more than once in the same place. */
703 dup = failtable_get(&failtable, call);
705 trace("Not failing %c due to duplicate\n",
706 info_to_arg[call->type]);
707 return call->fail = false;
711 switch (failtest_hook(&history)) {
718 trace("Not failing %c due to failhook return\n",
719 info_to_arg[call->type]);
727 /* Add it to our table of calls. */
728 failtable_add(&failtable, call);
730 /* We're going to fail in the child. */
732 if (pipe(control) != 0 || pipe(output) != 0)
733 err(1, "opening pipe");
735 /* Move out the way, to high fds. */
736 control[0] = move_fd_to_high(control[0]);
737 control[1] = move_fd_to_high(control[1]);
738 output[0] = move_fd_to_high(output[0]);
739 output[1] = move_fd_to_high(output[1]);
741 /* Prevent double-printing (in child and parent) */
748 err(1, "forking failed");
756 struct failtest_call *c;
758 c = tlist_tail(&history, list);
759 diff = time_sub(time_now(), start);
760 failpath = failpath_string();
761 p = strrchr(c->file, '/');
766 trace("%u->%u (%u.%02u): %s (%s:%u)\n",
768 (int)diff.tv_sec, (int)diff.tv_usec / 10000,
769 failpath, p, c->line);
772 /* From here on, we have to clean up! */
773 our_history_start = tlist_tail(&history, list);
776 /* Don't swallow stderr if we're tracing. */
778 dup2(output[1], STDOUT_FILENO);
779 dup2(output[1], STDERR_FILENO);
780 if (output[1] != STDOUT_FILENO
781 && output[1] != STDERR_FILENO)
784 control_fd = move_fd_to_high(control[1]);
786 /* Forget any of our parent's saved files. */
787 free_mmapped_files(false);
789 /* Now, save any files we need to. */
790 save_mmapped_files();
792 /* Failed calls can't leak. */
793 call->can_leak = false;
798 signal(SIGUSR1, hand_down);
803 /* We grab output so we can display it; we grab writes so we
806 struct pollfd pfd[2];
809 pfd[0].fd = output[0];
810 pfd[0].events = POLLIN|POLLHUP;
811 pfd[1].fd = control[0];
812 pfd[1].events = POLLIN|POLLHUP;
815 ret = poll(pfd, 1, failtest_timeout_ms);
817 ret = poll(pfd, 2, failtest_timeout_ms);
824 err(1, "Poll returned %i", ret);
827 if (pfd[0].revents & POLLIN) {
830 out = realloc(out, outlen + 8192);
831 len = read(output[0], out + outlen, 8192);
833 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
834 if (read_all(control[0], &type, sizeof(type))) {
836 if (!read_write_info(control[0]))
838 } else if (type == RELEASE_LOCKS) {
840 /* FIXME: Tell them we're done... */
843 } else if (pfd[0].revents & POLLHUP) {
846 } while (type != FAILURE);
850 waitpid(child, &status, 0);
851 if (!WIFEXITED(status)) {
852 if (WTERMSIG(status) == SIGUSR1)
853 child_fail(out, outlen, "Timed out");
855 child_fail(out, outlen, "Killed by signal %u: ",
858 /* Child printed failure already, just pass up exit code. */
859 if (type == FAILURE) {
860 fprintf(stderr, "%.*s", (int)outlen, out);
862 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
864 if (WEXITSTATUS(status) != 0)
865 child_fail(out, outlen, "Exited with status %i: ",
866 WEXITSTATUS(status));
869 signal(SIGUSR1, SIG_DFL);
871 /* Only child does probe. */
874 /* We continue onwards without failing. */
879 static void cleanup_calloc(struct calloc_call *call, bool restore)
881 trace("undoing calloc %p\n", call->ret);
885 void *failtest_calloc(size_t nmemb, size_t size,
886 const char *file, unsigned line)
888 struct failtest_call *p;
889 struct calloc_call call;
892 p = add_history(FAILTEST_CALLOC, true, file, line, &call);
894 if (should_fail(p)) {
895 p->u.calloc.ret = NULL;
898 p->u.calloc.ret = calloc(nmemb, size);
899 set_cleanup(p, cleanup_calloc, struct calloc_call);
901 trace("calloc %zu x %zu %s:%u -> %p\n",
902 nmemb, size, file, line, p->u.calloc.ret);
904 return p->u.calloc.ret;
907 static void cleanup_malloc(struct malloc_call *call, bool restore)
909 trace("undoing malloc %p\n", call->ret);
913 void *failtest_malloc(size_t size, const char *file, unsigned line)
915 struct failtest_call *p;
916 struct malloc_call call;
919 p = add_history(FAILTEST_MALLOC, true, file, line, &call);
920 if (should_fail(p)) {
921 p->u.malloc.ret = NULL;
924 p->u.malloc.ret = malloc(size);
925 set_cleanup(p, cleanup_malloc, struct malloc_call);
927 trace("malloc %zu %s:%u -> %p\n",
928 size, file, line, p->u.malloc.ret);
930 return p->u.malloc.ret;
933 static void cleanup_realloc(struct realloc_call *call, bool restore)
935 trace("undoing realloc %p\n", call->ret);
939 /* Walk back and find out if we got this ptr from a previous routine. */
940 static void fixup_ptr_history(void *ptr, const char *why)
942 struct failtest_call *i;
944 /* Start at end of history, work back. */
945 tlist_for_each_rev(&history, i, list) {
947 case FAILTEST_REALLOC:
948 if (i->u.realloc.ret == ptr) {
949 trace("found realloc %p %s:%u matching %s\n",
950 ptr, i->file, i->line, why);
956 case FAILTEST_MALLOC:
957 if (i->u.malloc.ret == ptr) {
958 trace("found malloc %p %s:%u matching %s\n",
959 ptr, i->file, i->line, why);
965 case FAILTEST_CALLOC:
966 if (i->u.calloc.ret == ptr) {
967 trace("found calloc %p %s:%u matching %s\n",
968 ptr, i->file, i->line, why);
978 trace("Did not find %p matching %s\n", ptr, why);
981 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
983 struct failtest_call *p;
984 struct realloc_call call;
986 p = add_history(FAILTEST_REALLOC, true, file, line, &call);
988 /* FIXME: Try one child moving allocation, one not. */
989 if (should_fail(p)) {
990 p->u.realloc.ret = NULL;
993 /* Don't catch this one in the history fixup... */
994 p->u.realloc.ret = NULL;
995 fixup_ptr_history(ptr, "realloc");
996 p->u.realloc.ret = realloc(ptr, size);
997 set_cleanup(p, cleanup_realloc, struct realloc_call);
999 trace("realloc %p %s:%u -> %p\n",
1000 ptr, file, line, p->u.realloc.ret);
1002 return p->u.realloc.ret;
1005 /* FIXME: Record free, so we can terminate fixup_ptr_history correctly.
1006 * If there's an alloc we don't see, it could get confusing if it matches
1007 * a previous allocation we did see. */
1008 void failtest_free(void *ptr)
1010 fixup_ptr_history(ptr, "free");
1011 trace("free %p\n", ptr);
1016 static struct contents_saved *save_file(const char *pathname)
1019 struct contents_saved *s;
1021 fd = open(pathname, O_RDONLY);
1025 s = save_contents(pathname, fd, lseek(fd, 0, SEEK_END), 0,
1026 "open with O_TRUNC");
1031 /* Optimization: don't create a child for an open which *we know*
1032 * would fail anyway. */
1033 static bool open_would_fail(const char *pathname, int flags)
1035 if ((flags & O_ACCMODE) == O_RDONLY)
1036 return access(pathname, R_OK) != 0;
1037 if (!(flags & O_CREAT)) {
1038 if ((flags & O_ACCMODE) == O_WRONLY)
1039 return access(pathname, W_OK) != 0;
1040 if ((flags & O_ACCMODE) == O_RDWR)
1041 return access(pathname, W_OK) != 0
1042 || access(pathname, R_OK) != 0;
1044 /* FIXME: We could check if it exists, for O_CREAT|O_EXCL */
1048 static void cleanup_open(struct open_call *call, bool restore)
1050 if (restore && call->saved)
1051 restore_contents(container_of(call, struct failtest_call,
1053 call->saved, false, "open with O_TRUNC");
1054 if (!call->closed) {
1055 trace("Cleaning up open %s by closing fd %i\n",
1056 call->pathname, call->ret);
1058 call->closed = true;
1063 int failtest_open(const char *pathname,
1064 const char *file, unsigned line, ...)
1066 struct failtest_call *p;
1067 struct open_call call;
1070 call.pathname = strdup(pathname);
1072 call.flags = va_arg(ap, int);
1073 call.always_save = false;
1074 call.closed = false;
1075 if (call.flags & O_CREAT) {
1076 call.mode = va_arg(ap, int);
1079 p = add_history(FAILTEST_OPEN, true, file, line, &call);
1080 /* Avoid memory leak! */
1081 if (p == &unrecorded_call)
1082 free((char *)call.pathname);
1084 if (should_fail(p)) {
1085 /* Don't bother inserting failures that would happen anyway. */
1086 if (open_would_fail(pathname, call.flags)) {
1087 trace("Open would have failed anyway: stopping\n");
1088 failtest_cleanup(true, 0);
1091 /* FIXME: Play with error codes? */
1094 /* Save the old version if they're truncating it. */
1095 if (call.flags & O_TRUNC)
1096 p->u.open.saved = save_file(pathname);
1098 p->u.open.saved = NULL;
1099 p->u.open.ret = open(pathname, call.flags, call.mode);
1100 if (p->u.open.ret == -1) {
1101 p->u.open.closed = true;
1102 p->can_leak = false;
1104 set_cleanup(p, cleanup_open, struct open_call);
1107 trace("open %s %s:%u -> %i (opener %p)\n",
1108 pathname, file, line, p->u.open.ret, &p->u.open);
1110 return p->u.open.ret;
1113 static void cleanup_mmap(struct mmap_call *mmap, bool restore)
1115 trace("cleaning up mmap @%p (opener %p)\n",
1116 mmap->ret, mmap->opener);
1118 restore_contents(mmap->opener, mmap->saved, false, "mmap");
1122 void *failtest_mmap(void *addr, size_t length, int prot, int flags,
1123 int fd, off_t offset, const char *file, unsigned line)
1125 struct failtest_call *p;
1126 struct mmap_call call;
1129 call.length = length;
1132 call.offset = offset;
1134 call.opener = opener_of(fd);
1136 /* If we don't know what file it was, don't fail. */
1139 fwarnx("failtest_mmap: couldn't figure out source for"
1140 " fd %i at %s:%u", fd, file, line);
1142 addr = mmap(addr, length, prot, flags, fd, offset);
1143 trace("mmap of fd %i -> %p (opener = NULL)\n", fd, addr);
1147 p = add_history(FAILTEST_MMAP, false, file, line, &call);
1148 if (should_fail(p)) {
1149 p->u.mmap.ret = MAP_FAILED;
1152 p->u.mmap.ret = mmap(addr, length, prot, flags, fd, offset);
1153 /* Save contents if we're writing to a normal file */
1154 if (p->u.mmap.ret != MAP_FAILED
1155 && (prot & PROT_WRITE)
1156 && call.opener->type == FAILTEST_OPEN) {
1157 const char *fname = call.opener->u.open.pathname;
1158 p->u.mmap.saved = save_contents(fname, fd, length,
1159 offset, "being mmapped");
1160 set_cleanup(p, cleanup_mmap, struct mmap_call);
1163 trace("mmap of fd %i %s:%u -> %p (opener = %p)\n",
1164 fd, file, line, addr, call.opener);
1166 return p->u.mmap.ret;
1169 static void cleanup_pipe(struct pipe_call *call, bool restore)
1171 trace("cleaning up pipe fd=%i%s,%i%s\n",
1172 call->fds[0], call->closed[0] ? "(already closed)" : "",
1173 call->fds[1], call->closed[1] ? "(already closed)" : "");
1174 if (!call->closed[0])
1175 close(call->fds[0]);
1176 if (!call->closed[1])
1177 close(call->fds[1]);
1180 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
1182 struct failtest_call *p;
1183 struct pipe_call call;
1185 p = add_history(FAILTEST_PIPE, true, file, line, &call);
1186 if (should_fail(p)) {
1188 /* FIXME: Play with error codes? */
1191 p->u.pipe.ret = pipe(p->u.pipe.fds);
1192 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
1193 set_cleanup(p, cleanup_pipe, struct pipe_call);
1196 trace("pipe %s:%u -> %i,%i\n", file, line,
1197 p->u.pipe.ret ? -1 : p->u.pipe.fds[0],
1198 p->u.pipe.ret ? -1 : p->u.pipe.fds[1]);
1200 /* This causes valgrind to notice if they use pipefd[] after failure */
1201 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
1203 return p->u.pipe.ret;
1206 static void cleanup_read(struct read_call *call, bool restore)
1209 trace("cleaning up read on fd %i: seeking to %llu\n",
1210 call->fd, (long long)call->off);
1212 /* Read (not readv!) moves file offset! */
1213 if (lseek(call->fd, call->off, SEEK_SET) != call->off) {
1214 fwarn("Restoring lseek pointer failed (read)");
1219 static ssize_t failtest_add_read(int fd, void *buf, size_t count, off_t off,
1220 bool is_pread, const char *file, unsigned line)
1222 struct failtest_call *p;
1223 struct read_call call;
1228 p = add_history(FAILTEST_READ, false, file, line, &call);
1230 /* FIXME: Try partial read returns. */
1231 if (should_fail(p)) {
1236 p->u.read.ret = pread(fd, buf, count, off);
1238 p->u.read.ret = read(fd, buf, count);
1239 if (p->u.read.ret != -1)
1240 set_cleanup(p, cleanup_read, struct read_call);
1243 trace("%sread %s:%u fd %i %zu@%llu -> %i\n",
1244 is_pread ? "p" : "", file, line, fd, count, (long long)off,
1247 return p->u.read.ret;
1250 static void cleanup_write(struct write_call *write, bool restore)
1252 trace("cleaning up write on %s\n", write->opener->u.open.pathname);
1254 restore_contents(write->opener, write->saved, !write->is_pwrite,
1259 static ssize_t failtest_add_write(int fd, const void *buf,
1260 size_t count, off_t off,
1262 const char *file, unsigned line)
1264 struct failtest_call *p;
1265 struct write_call call;
1271 call.is_pwrite = is_pwrite;
1272 call.opener = opener_of(fd);
1273 p = add_history(FAILTEST_WRITE, false, file, line, &call);
1275 /* If we're a child, we need to make sure we write the same thing
1276 * to non-files as the parent does, so tell it. */
1277 if (control_fd != -1 && off == (off_t)-1) {
1278 enum info_type type = WRITE;
1280 write_all(control_fd, &type, sizeof(type));
1281 write_all(control_fd, &p->u.write, sizeof(p->u.write));
1282 write_all(control_fd, buf, count);
1285 /* FIXME: Try partial write returns. */
1286 if (should_fail(p)) {
1287 p->u.write.ret = -1;
1291 assert(call.opener == p->u.write.opener);
1293 if (p->u.write.opener) {
1294 is_file = (p->u.write.opener->type == FAILTEST_OPEN);
1296 /* We can't unwind it, so at least check same
1297 * in parent and child. */
1301 /* FIXME: We assume same write order in parent and child */
1302 if (!is_file && child_writes_num != 0) {
1303 if (child_writes[0].fd != fd)
1304 errx(1, "Child wrote to fd %u, not %u?",
1305 child_writes[0].fd, fd);
1306 if (child_writes[0].off != p->u.write.off)
1307 errx(1, "Child wrote to offset %zu, not %zu?",
1308 (size_t)child_writes[0].off,
1309 (size_t)p->u.write.off);
1310 if (child_writes[0].count != count)
1311 errx(1, "Child wrote length %zu, not %zu?",
1312 child_writes[0].count, count);
1313 if (memcmp(child_writes[0].buf, buf, count)) {
1315 "Child wrote differently to"
1316 " fd %u than we did!\n", fd);
1318 free((char *)child_writes[0].buf);
1320 memmove(&child_writes[0], &child_writes[1],
1321 sizeof(child_writes[0]) * child_writes_num);
1323 /* Child wrote it already. */
1324 trace("write %s:%i on fd %i already done by child\n",
1326 p->u.write.ret = count;
1328 return p->u.write.ret;
1332 p->u.write.saved = save_contents(call.opener->u.open.pathname,
1334 "being overwritten");
1335 set_cleanup(p, cleanup_write, struct write_call);
1338 /* Though off is current seek ptr for write case, we need to
1339 * move it. write() does that for us. */
1340 if (p->u.write.is_pwrite)
1341 p->u.write.ret = pwrite(fd, buf, count, off);
1343 p->u.write.ret = write(fd, buf, count);
1345 trace("%swrite %s:%i %zu@%llu on fd %i -> %i\n",
1346 p->u.write.is_pwrite ? "p" : "",
1347 file, line, count, (long long)off, fd, p->u.write.ret);
1349 return p->u.write.ret;
1352 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t offset,
1353 const char *file, unsigned line)
1355 return failtest_add_write(fd, buf, count, offset, true, file, line);
1358 ssize_t failtest_write(int fd, const void *buf, size_t count,
1359 const char *file, unsigned line)
1361 return failtest_add_write(fd, buf, count, lseek(fd, 0, SEEK_CUR), false,
1365 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
1366 const char *file, unsigned line)
1368 return failtest_add_read(fd, buf, count, off, true, file, line);
1371 ssize_t failtest_read(int fd, void *buf, size_t count,
1372 const char *file, unsigned line)
1374 return failtest_add_read(fd, buf, count, lseek(fd, 0, SEEK_CUR), false,
1378 static struct lock_info *WARN_UNUSED_RESULT
1379 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
1382 struct lock_info *l;
1384 for (i = 0; i < lock_num; i++) {
1389 /* Four cases we care about:
1403 if (start > l->start && end < l->end) {
1404 /* Mid overlap: trim entry, add new one. */
1405 off_t new_start, new_end;
1406 new_start = end + 1;
1408 trace("splitting lock on fd %i from %llu-%llu"
1410 fd, (long long)l->start, (long long)l->end,
1411 (long long)l->start, (long long)start - 1);
1413 locks = add_lock(locks,
1414 fd, new_start, new_end, l->type);
1416 } else if (start <= l->start && end >= l->end) {
1417 /* Total overlap: eliminate entry. */
1418 trace("erasing lock on fd %i %llu-%llu\n",
1419 fd, (long long)l->start, (long long)l->end);
1422 } else if (end >= l->start && end < l->end) {
1423 trace("trimming lock on fd %i from %llu-%llu"
1425 fd, (long long)l->start, (long long)l->end,
1426 (long long)end + 1, (long long)l->end);
1427 /* Start overlap: trim entry. */
1429 } else if (start > l->start && start <= l->end) {
1430 trace("trimming lock on fd %i from %llu-%llu"
1432 fd, (long long)l->start, (long long)l->end,
1433 (long long)l->start, (long long)start - 1);
1434 /* End overlap: trim entry. */
1437 /* Nothing left? Remove it. */
1438 if (l->end < l->start) {
1439 trace("forgetting lock on fd %i\n", fd);
1440 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
1445 if (type != F_UNLCK) {
1446 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
1447 l = &locks[lock_num++];
1452 trace("new lock on fd %i %llu-%llu\n",
1453 fd, (long long)l->start, (long long)l->end);
1458 /* We trap this so we can record it: we don't fail it. */
1459 int failtest_close(int fd, const char *file, unsigned line)
1461 struct close_call call;
1462 struct failtest_call *p, *opener;
1464 /* Do this before we add ourselves to history! */
1465 opener = opener_of(fd);
1468 p = add_history(FAILTEST_CLOSE, false, file, line, &call);
1471 /* Consume close from failpath (shouldn't tell us to fail). */
1472 if (following_path()) {
1477 trace("close on fd %i\n", fd);
1481 /* Mark opener as not leaking, remove its cleanup function. */
1483 trace("close on fd %i found opener %p\n", fd, opener);
1484 if (opener->type == FAILTEST_PIPE) {
1486 if (opener->u.pipe.fds[0] == fd) {
1487 assert(!opener->u.pipe.closed[0]);
1488 opener->u.pipe.closed[0] = true;
1489 } else if (opener->u.pipe.fds[1] == fd) {
1490 assert(!opener->u.pipe.closed[1]);
1491 opener->u.pipe.closed[1] = true;
1494 opener->can_leak = (!opener->u.pipe.closed[0]
1495 || !opener->u.pipe.closed[1]);
1496 } else if (opener->type == FAILTEST_OPEN) {
1497 opener->u.open.closed = true;
1498 opener->can_leak = false;
1503 /* Restore offset now, in case parent shared (can't do after close!). */
1504 if (control_fd != -1) {
1505 struct failtest_call *i;
1507 tlist_for_each_rev(&history, i, list) {
1508 if (i == our_history_start)
1512 if (i->type == FAILTEST_LSEEK && i->u.lseek.fd == fd) {
1513 trace("close on fd %i undoes lseek\n", fd);
1514 /* This seeks back. */
1515 i->cleanup(&i->u, true);
1517 } else if (i->type == FAILTEST_WRITE
1518 && i->u.write.fd == fd
1519 && !i->u.write.is_pwrite) {
1520 trace("close on fd %i undoes write"
1521 " offset change\n", fd);
1522 /* Write (not pwrite!) moves file offset! */
1523 if (lseek(fd, i->u.write.off, SEEK_SET)
1524 != i->u.write.off) {
1525 fwarn("Restoring lseek pointer failed (write)");
1527 } else if (i->type == FAILTEST_READ
1528 && i->u.read.fd == fd) {
1529 /* preads don't *have* cleanups */
1531 trace("close on fd %i undoes read"
1532 " offset change\n", fd);
1533 /* This seeks back. */
1534 i->cleanup(&i->u, true);
1541 /* Close unlocks everything. */
1542 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
1546 /* Zero length means "to end of file" */
1547 static off_t end_of(off_t start, off_t len)
1551 return start + len - 1;
1554 /* FIXME: This only handles locks, really. */
1555 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
1557 struct failtest_call *p;
1558 struct fcntl_call call;
1564 /* Argument extraction. */
1569 call.arg.l = va_arg(ap, long);
1571 trace("fcntl on fd %i F_SETFL/F_SETFD\n", fd);
1572 return fcntl(fd, cmd, call.arg.l);
1575 trace("fcntl on fd %i F_GETFL/F_GETFD\n", fd);
1576 return fcntl(fd, cmd);
1578 trace("fcntl on fd %i F_GETLK\n", fd);
1581 call.arg.fl = *va_arg(ap, struct flock *);
1583 return fcntl(fd, cmd, &call.arg.fl);
1586 trace("fcntl on fd %i F_SETLK%s\n",
1587 fd, cmd == F_SETLKW ? "W" : "");
1589 call.arg.fl = *va_arg(ap, struct flock *);
1593 /* This means you need to implement it here. */
1594 err(1, "failtest: unknown fcntl %u", cmd);
1597 p = add_history(FAILTEST_FCNTL, false, file, line, &call);
1599 if (should_fail(p)) {
1600 p->u.fcntl.ret = -1;
1601 if (p->u.fcntl.cmd == F_SETLK)
1607 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
1608 &p->u.fcntl.arg.fl);
1609 if (p->u.fcntl.ret == -1)
1612 /* We don't handle anything else yet. */
1613 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1614 locks = add_lock(locks,
1616 p->u.fcntl.arg.fl.l_start,
1617 end_of(p->u.fcntl.arg.fl.l_start,
1618 p->u.fcntl.arg.fl.l_len),
1619 p->u.fcntl.arg.fl.l_type);
1622 trace("fcntl on fd %i -> %i\n", fd, p->u.fcntl.ret);
1624 return p->u.fcntl.ret;
1627 static void cleanup_lseek(struct lseek_call *call, bool restore)
1630 trace("cleaning up lseek on fd %i -> %llu\n",
1631 call->fd, (long long)call->old_off);
1632 if (lseek(call->fd, call->old_off, SEEK_SET) != call->old_off)
1633 fwarn("Restoring lseek pointer failed");
1637 /* We trap this so we can undo it: we don't fail it. */
1638 off_t failtest_lseek(int fd, off_t offset, int whence, const char *file,
1641 struct failtest_call *p;
1642 struct lseek_call call;
1644 call.offset = offset;
1645 call.whence = whence;
1646 call.old_off = lseek(fd, 0, SEEK_CUR);
1648 p = add_history(FAILTEST_LSEEK, false, file, line, &call);
1651 /* Consume lseek from failpath. */
1656 p->u.lseek.ret = lseek(fd, offset, whence);
1658 if (p->u.lseek.ret != (off_t)-1)
1659 set_cleanup(p, cleanup_lseek, struct lseek_call);
1661 trace("lseek %s:%u on fd %i from %llu to %llu%s\n",
1662 file, line, fd, (long long)call.old_off, (long long)offset,
1663 whence == SEEK_CUR ? " (from current off)" :
1664 whence == SEEK_END ? " (from end)" :
1665 whence == SEEK_SET ? "" : " (invalid whence)");
1666 return p->u.lseek.ret;
1670 pid_t failtest_getpid(const char *file, unsigned line)
1672 /* You must call failtest_init first! */
1677 void failtest_init(int argc, char *argv[])
1681 orig_pid = getpid();
1683 warnf = fdopen(move_fd_to_high(dup(STDERR_FILENO)), "w");
1684 for (i = 1; i < argc; i++) {
1685 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1686 failpath = argv[i] + strlen("--failpath=");
1687 } else if (strcmp(argv[i], "--trace") == 0) {
1689 failtest_timeout_ms = -1;
1690 } else if (!strncmp(argv[i], "--debugpath=",
1691 strlen("--debugpath="))) {
1692 debugpath = argv[i] + strlen("--debugpath=");
1695 failtable_init(&failtable);
1699 bool failtest_has_failed(void)
1701 return control_fd != -1;
1704 void failtest_exit(int status)
1706 trace("failtest_exit with status %i\n", status);
1707 if (failtest_exit_check) {
1708 if (!failtest_exit_check(&history))
1709 child_fail(NULL, 0, "failtest_exit_check failed\n");
1712 failtest_cleanup(false, status);