10 #include <sys/types.h>
15 #include <ccan/read_write_all/read_write_all.h>
16 #include <ccan/failtest/failtest_proto.h>
17 #include <ccan/failtest/failtest.h>
18 #include <ccan/build_assert/build_assert.h>
20 enum failtest_result (*failtest_hook)(struct failtest_call *, unsigned);
22 static int tracefd = -1;
24 unsigned int failtest_timeout_ms = 20000;
27 const char *debugpath;
39 /* end is inclusive: you can't have a 0-byte lock. */
44 bool (*failtest_exit_check)(struct failtest_call *history, unsigned num);
46 static struct failtest_call *history = NULL;
47 static unsigned int history_num = 0;
48 static int control_fd = -1;
49 static struct timeval start;
50 static unsigned int probe_count = 0;
52 static struct write_call *child_writes = NULL;
53 static unsigned int child_writes_num = 0;
55 static pid_t lock_owner;
56 static struct lock_info *locks = NULL;
57 static unsigned int lock_num = 0;
59 static const char info_to_arg[] = "mceoxprwf";
61 /* Dummy call used for failtest_undo wrappers. */
62 static struct failtest_call unrecorded_call;
64 static struct failtest_call *add_history_(enum failtest_call_type type,
70 /* NULL file is how we suppress failure. */
72 return &unrecorded_call;
74 history = realloc(history, (history_num + 1) * sizeof(*history));
75 history[history_num].type = type;
76 history[history_num].file = file;
77 history[history_num].line = line;
78 history[history_num].cleanup = NULL;
79 memcpy(&history[history_num].u, elem, elem_size);
80 return &history[history_num++];
83 #define add_history(type, file, line, elem) \
84 add_history_((type), (file), (line), (elem), sizeof(*(elem)))
86 #define set_cleanup(call, clean, type) \
87 (call)->cleanup = (void *)((void)sizeof(clean((type *)NULL)), (clean))
89 static bool read_write_info(int fd)
94 /* We don't need all of this, but it's simple. */
95 child_writes = realloc(child_writes,
96 (child_writes_num+1) * sizeof(child_writes[0]));
97 w = &child_writes[child_writes_num];
98 if (!read_all(fd, w, sizeof(*w)))
101 w->buf = buf = malloc(w->count);
102 if (!read_all(fd, buf, w->count))
109 static char *failpath_string(void)
112 char *ret = malloc(history_num + 1);
114 for (i = 0; i < history_num; i++) {
115 ret[i] = info_to_arg[history[i].type];
117 ret[i] = toupper(ret[i]);
123 static void tell_parent(enum info_type type)
125 if (control_fd != -1)
126 write_all(control_fd, &type, sizeof(type));
129 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
132 char *path = failpath_string();
135 vfprintf(stderr, fmt, ap);
138 fprintf(stderr, "%.*s", (int)outlen, out);
139 printf("To reproduce: --failpath=%s\n", path);
141 tell_parent(FAILURE);
147 static void hand_down(int signal)
152 static void release_locks(void)
154 /* Locks were never acquired/reacquired? */
158 /* We own them? Release them all. */
159 if (lock_owner == getpid()) {
163 fl.l_whence = SEEK_SET;
167 for (i = 0; i < lock_num; i++)
168 fcntl(locks[i].fd, F_SETLK, &fl);
170 /* Our parent must have them; pass request up. */
171 enum info_type type = RELEASE_LOCKS;
172 assert(control_fd != -1);
173 write_all(control_fd, &type, sizeof(type));
178 /* off_t is a signed type. Getting its max is non-trivial. */
179 static off_t off_max(void)
181 BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
182 if (sizeof(off_t) == 4)
183 return (off_t)0x7FFFFFF;
185 return (off_t)0x7FFFFFFFFFFFFFFULL;
188 static void get_locks(void)
193 if (lock_owner == getpid())
196 if (lock_owner != 0) {
197 enum info_type type = RELEASE_LOCKS;
198 assert(control_fd != -1);
199 write_all(control_fd, &type, sizeof(type));
202 fl.l_whence = SEEK_SET;
204 for (i = 0; i < lock_num; i++) {
205 fl.l_type = locks[i].type;
206 fl.l_start = locks[i].start;
207 if (locks[i].end == off_max())
210 fl.l_len = locks[i].end - locks[i].start + 1;
212 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
215 lock_owner = getpid();
218 static void trace_str(const char *str)
222 while ((ret = write(tracefd, str, strlen(str))) > 0) {
227 err(1, "Writing trace.");
231 struct saved_file *next;
237 static struct saved_file *save_file(struct saved_file *next, int fd)
239 struct saved_file *s = malloc(sizeof(*s));
243 s->off = lseek(fd, 0, SEEK_CUR);
244 /* Special file? Erk... */
245 assert(s->off != -1);
246 s->len = lseek(fd, 0, SEEK_END);
247 lseek(fd, 0, SEEK_SET);
248 s->contents = malloc(s->len);
249 read(fd, s->contents, s->len);
250 lseek(fd, s->off, SEEK_SET);
254 /* We have little choice but to save and restore open files: mmap means we
255 * can really intercept changes in the child.
257 * We could do non-mmap'ed files on demand, however. */
258 static struct saved_file *save_files(void)
260 struct saved_file *files = NULL;
263 /* Figure out the set of live fds. */
264 for (i = history_num - 2; i >= 0; i--) {
265 if (history[i].type == FAILTEST_OPEN) {
266 int fd = history[i].u.open.ret;
267 /* Only do successful, writable fds. */
271 /* If it was closed, cleanup == NULL. */
272 if (!history[i].cleanup)
275 if ((history[i].u.open.flags & O_RDWR) == O_RDWR) {
276 files = save_file(files, fd);
277 } else if ((history[i].u.open.flags & O_WRONLY)
279 /* FIXME: Handle O_WRONLY. Open with O_RDWR? */
288 static void restore_files(struct saved_file *s)
291 struct saved_file *next = s->next;
293 lseek(s->fd, 0, SEEK_SET);
294 write(s->fd, s->contents, s->len);
295 ftruncate(s->fd, s->len);
297 lseek(s->fd, s->off, SEEK_SET);
303 /* Free up memory, so valgrind doesn't report leaks. */
304 static void free_everything(void)
308 /* We don't do this in cleanup: needed even for failed opens. */
309 for (i = 0; i < history_num; i++) {
310 if (history[i].type == FAILTEST_OPEN)
311 free((char *)history[i].u.open.pathname);
316 static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
320 /* For children, we don't care if they "failed" the testing. */
321 if (control_fd != -1)
327 /* Cleanup everything, in reverse order. */
328 for (i = history_num - 1; i >= 0; i--) {
329 if (!history[i].cleanup)
331 if (!forced_cleanup) {
332 printf("Leak at %s:%u\n",
333 history[i].file, history[i].line);
336 history[i].cleanup(&history[i].u);
340 tell_parent(SUCCESS);
344 static bool should_fail(struct failtest_call *call)
347 int control[2], output[2];
348 enum info_type type = UNEXPECTED;
351 struct saved_file *files;
353 /* Are we probing? */
354 if (probe_count && --probe_count == 0)
355 failtest_cleanup(true, 0);
357 if (call == &unrecorded_call)
361 /* + means continue after end, like normal. */
362 if (*failpath == '+')
365 if (tolower(*failpath) != info_to_arg[call->type])
366 errx(1, "Failpath expected '%c' got '%c'\n",
367 info_to_arg[call->type], *failpath);
368 call->fail = isupper(*(failpath++));
373 /* Attach debugger if they asked for it. */
374 if (debugpath && history_num == strlen(debugpath)) {
377 for (i = 0; i < history_num; i++) {
378 char c = info_to_arg[history[i].type];
381 if (c != debugpath[i])
384 if (i == history_num) {
388 signal(SIGUSR1, SIG_IGN);
389 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
397 switch (failtest_hook(history, history_num)) {
404 /* Already down probe path? Stop now. */
406 failtest_cleanup(true, 0);
407 /* FIXME: We should run *parent* and run probe until
408 * calls match up again. */
416 files = save_files();
418 /* We're going to fail in the child. */
420 if (pipe(control) != 0 || pipe(output) != 0)
421 err(1, "opening pipe");
423 /* Prevent double-printing (in child and parent) */
427 err(1, "forking failed");
433 gettimeofday(&now, NULL);
434 if (now.tv_usec < start.tv_usec) {
436 now.tv_usec += 1000000;
438 now.tv_usec -= start.tv_usec;
439 now.tv_sec -= start.tv_sec;
440 sprintf(str, "%u (%u.%02u): ", getpid(),
441 (int)now.tv_sec, (int)now.tv_usec / 10000);
443 p = failpath_string();
447 p = strchr(history[history_num-1].file, '/');
451 trace_str(history[history_num-1].file);
452 sprintf(str, ":%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);
489 if (pfd[0].revents & POLLIN) {
492 out = realloc(out, outlen + 8192);
493 len = read(output[0], out + outlen, 8192);
495 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
496 if (read_all(control[0], &type, sizeof(type))) {
498 if (!read_write_info(control[0]))
500 } else if (type == RELEASE_LOCKS) {
502 /* FIXME: Tell them we're done... */
505 } else if (pfd[0].revents & POLLHUP) {
508 } while (type != FAILURE);
512 waitpid(child, &status, 0);
513 if (!WIFEXITED(status)) {
514 if (WTERMSIG(status) == SIGUSR1)
515 child_fail(out, outlen, "Timed out");
517 child_fail(out, outlen, "Killed by signal %u: ",
520 /* Child printed failure already, just pass up exit code. */
521 if (type == FAILURE) {
522 fprintf(stderr, "%.*s", (int)outlen, out);
524 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
526 if (WEXITSTATUS(status) != 0)
527 child_fail(out, outlen, "Exited with status %i: ",
528 WEXITSTATUS(status));
531 signal(SIGUSR1, SIG_DFL);
533 restore_files(files);
535 /* We continue onwards without failing. */
540 static void cleanup_calloc(struct calloc_call *call)
545 void *failtest_calloc(size_t nmemb, size_t size,
546 const char *file, unsigned line)
548 struct failtest_call *p;
549 struct calloc_call call;
552 p = add_history(FAILTEST_CALLOC, file, line, &call);
554 if (should_fail(p)) {
555 p->u.calloc.ret = NULL;
558 p->u.calloc.ret = calloc(nmemb, size);
559 set_cleanup(p, cleanup_calloc, struct calloc_call);
562 return p->u.calloc.ret;
565 static void cleanup_malloc(struct malloc_call *call)
570 void *failtest_malloc(size_t size, const char *file, unsigned line)
572 struct failtest_call *p;
573 struct malloc_call call;
576 p = add_history(FAILTEST_MALLOC, file, line, &call);
577 if (should_fail(p)) {
578 p->u.calloc.ret = NULL;
581 p->u.calloc.ret = malloc(size);
582 set_cleanup(p, cleanup_malloc, struct malloc_call);
585 return p->u.calloc.ret;
588 static void cleanup_realloc(struct realloc_call *call)
593 /* Walk back and find out if we got this ptr from a previous routine. */
594 static void fixup_ptr_history(void *ptr, unsigned int last)
598 /* Start at end of history, work back. */
599 for (i = last - 1; i >= 0; i--) {
600 switch (history[i].type) {
601 case FAILTEST_REALLOC:
602 if (history[i].u.realloc.ret == ptr) {
603 history[i].cleanup = NULL;
607 case FAILTEST_MALLOC:
608 if (history[i].u.malloc.ret == ptr) {
609 history[i].cleanup = NULL;
613 case FAILTEST_CALLOC:
614 if (history[i].u.calloc.ret == ptr) {
615 history[i].cleanup = NULL;
625 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
627 struct failtest_call *p;
628 struct realloc_call call;
630 p = add_history(FAILTEST_REALLOC, file, line, &call);
632 /* FIXME: Try one child moving allocation, one not. */
633 if (should_fail(p)) {
634 p->u.realloc.ret = NULL;
637 fixup_ptr_history(ptr, history_num-1);
638 p->u.realloc.ret = realloc(ptr, size);
639 set_cleanup(p, cleanup_realloc, struct realloc_call);
642 return p->u.realloc.ret;
645 void failtest_free(void *ptr)
647 fixup_ptr_history(ptr, history_num);
651 static void cleanup_open(struct open_call *call)
656 int failtest_open(const char *pathname,
657 const char *file, unsigned line, ...)
659 struct failtest_call *p;
660 struct open_call call;
663 call.pathname = strdup(pathname);
665 call.flags = va_arg(ap, int);
666 if (call.flags & O_CREAT) {
667 call.mode = va_arg(ap, mode_t);
670 p = add_history(FAILTEST_OPEN, file, line, &call);
671 /* Avoid memory leak! */
672 if (p == &unrecorded_call)
673 free((char *)call.pathname);
674 p->u.open.ret = open(pathname, call.flags, call.mode);
676 if (!failpath && p->u.open.ret == -1) {
679 } else if (should_fail(p)) {
680 close(p->u.open.ret);
682 /* FIXME: Play with error codes? */
685 set_cleanup(p, cleanup_open, struct open_call);
688 return p->u.open.ret;
691 static void cleanup_pipe(struct pipe_call *call)
693 if (!call->closed[0])
695 if (!call->closed[1])
699 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
701 struct failtest_call *p;
702 struct pipe_call call;
704 p = add_history(FAILTEST_PIPE, file, line, &call);
705 if (should_fail(p)) {
707 /* FIXME: Play with error codes? */
710 p->u.pipe.ret = pipe(p->u.pipe.fds);
711 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
712 set_cleanup(p, cleanup_pipe, struct pipe_call);
714 /* This causes valgrind to notice if they use pipefd[] after failure */
715 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
717 return p->u.pipe.ret;
720 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
721 const char *file, unsigned line)
723 struct failtest_call *p;
724 struct read_call call;
729 p = add_history(FAILTEST_READ, file, line, &call);
731 /* FIXME: Try partial read returns. */
732 if (should_fail(p)) {
736 p->u.read.ret = pread(fd, buf, count, off);
739 return p->u.read.ret;
742 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
743 const char *file, unsigned line)
745 struct failtest_call *p;
746 struct write_call call;
752 p = add_history(FAILTEST_WRITE, file, line, &call);
754 /* If we're a child, we need to make sure we write the same thing
755 * to non-files as the parent does, so tell it. */
756 if (control_fd != -1 && off == (off_t)-1) {
757 enum info_type type = WRITE;
759 write_all(control_fd, &type, sizeof(type));
760 write_all(control_fd, &p->u.write, sizeof(p->u.write));
761 write_all(control_fd, buf, count);
764 /* FIXME: Try partial write returns. */
765 if (should_fail(p)) {
769 /* FIXME: We assume same write order in parent and child */
770 if (off == (off_t)-1 && child_writes_num != 0) {
771 if (child_writes[0].fd != fd)
772 errx(1, "Child wrote to fd %u, not %u?",
773 child_writes[0].fd, fd);
774 if (child_writes[0].off != p->u.write.off)
775 errx(1, "Child wrote to offset %zu, not %zu?",
776 (size_t)child_writes[0].off,
777 (size_t)p->u.write.off);
778 if (child_writes[0].count != count)
779 errx(1, "Child wrote length %zu, not %zu?",
780 child_writes[0].count, count);
781 if (memcmp(child_writes[0].buf, buf, count)) {
783 "Child wrote differently to"
784 " fd %u than we did!\n", fd);
786 free((char *)child_writes[0].buf);
788 memmove(&child_writes[0], &child_writes[1],
789 sizeof(child_writes[0]) * child_writes_num);
791 /* Is this is a socket or pipe, child wrote it
793 if (p->u.write.off == (off_t)-1) {
794 p->u.write.ret = count;
796 return p->u.write.ret;
799 p->u.write.ret = pwrite(fd, buf, count, off);
802 return p->u.write.ret;
805 ssize_t failtest_read(int fd, void *buf, size_t count,
806 const char *file, unsigned line)
808 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
812 ssize_t failtest_write(int fd, const void *buf, size_t count,
813 const char *file, unsigned line)
815 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
819 static struct lock_info *WARN_UNUSED_RESULT
820 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
825 for (i = 0; i < lock_num; i++) {
830 /* Four cases we care about:
844 if (start > l->start && end < l->end) {
845 /* Mid overlap: trim entry, add new one. */
846 off_t new_start, new_end;
850 locks = add_lock(locks,
851 fd, new_start, new_end, l->type);
853 } else if (start <= l->start && end >= l->end) {
854 /* Total overlap: eliminate entry. */
857 } else if (end >= l->start && end < l->end) {
858 /* Start overlap: trim entry. */
860 } else if (start > l->start && start <= l->end) {
861 /* End overlap: trim entry. */
864 /* Nothing left? Remove it. */
865 if (l->end < l->start) {
866 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
871 if (type != F_UNLCK) {
872 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
873 l = &locks[lock_num++];
882 /* We trap this so we can record it: we don't fail it. */
883 int failtest_close(int fd, const char *file, unsigned line)
886 struct close_call call;
887 struct failtest_call *p;
890 p = add_history(FAILTEST_CLOSE, file, line, &call);
893 /* Consume close from failpath. */
901 /* Trace history to find source of fd. */
902 for (i = history_num-1; i >= 0; i--) {
903 switch (history[i].type) {
906 if (history[i].u.pipe.fds[0] == fd) {
907 assert(!history[i].u.pipe.closed[0]);
908 history[i].u.pipe.closed[0] = true;
909 if (history[i].u.pipe.closed[1])
910 history[i].cleanup = NULL;
913 if (history[i].u.pipe.fds[1] == fd) {
914 assert(!history[i].u.pipe.closed[1]);
915 history[i].u.pipe.closed[1] = true;
916 if (history[i].u.pipe.closed[0])
917 history[i].cleanup = NULL;
922 if (history[i].u.open.ret == fd) {
923 assert((void *)history[i].cleanup
924 == (void *)cleanup_open);
925 history[i].cleanup = NULL;
935 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
939 /* Zero length means "to end of file" */
940 static off_t end_of(off_t start, off_t len)
944 return start + len - 1;
947 /* FIXME: This only handles locks, really. */
948 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
950 struct failtest_call *p;
951 struct fcntl_call call;
957 /* Argument extraction. */
962 call.arg.l = va_arg(ap, long);
964 return fcntl(fd, cmd, call.arg.l);
967 return fcntl(fd, cmd);
971 call.arg.fl = *va_arg(ap, struct flock *);
973 return fcntl(fd, cmd, &call.arg.fl);
977 call.arg.fl = *va_arg(ap, struct flock *);
981 /* This means you need to implement it here. */
982 err(1, "failtest: unknown fcntl %u", cmd);
985 p = add_history(FAILTEST_FCNTL, file, line, &call);
987 if (should_fail(p)) {
989 if (p->u.fcntl.cmd == F_SETLK)
995 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
997 if (p->u.fcntl.ret == -1)
1000 /* We don't handle anything else yet. */
1001 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1002 locks = add_lock(locks,
1004 p->u.fcntl.arg.fl.l_start,
1005 end_of(p->u.fcntl.arg.fl.l_start,
1006 p->u.fcntl.arg.fl.l_len),
1007 p->u.fcntl.arg.fl.l_type);
1011 return p->u.fcntl.ret;
1014 void failtest_init(int argc, char *argv[])
1018 for (i = 1; i < argc; i++) {
1019 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1020 failpath = argv[i] + strlen("--failpath=");
1021 } else if (strcmp(argv[i], "--tracepath") == 0) {
1022 tracefd = dup(STDERR_FILENO);
1023 failtest_timeout_ms = -1;
1024 } else if (!strncmp(argv[i], "--debugpath=",
1025 strlen("--debugpath="))) {
1026 debugpath = argv[i] + strlen("--debugpath=");
1029 gettimeofday(&start, NULL);
1032 void failtest_exit(int status)
1034 if (failtest_exit_check) {
1035 if (!failtest_exit_check(history, history_num))
1036 child_fail(NULL, 0, "failtest_exit_check failed\n");
1039 failtest_cleanup(false, status);