11 #include <sys/types.h>
16 #include <ccan/read_write_all/read_write_all.h>
17 #include <ccan/failtest/failtest_proto.h>
18 #include <ccan/failtest/failtest.h>
19 #include <ccan/build_assert/build_assert.h>
21 enum failtest_result (*failtest_hook)(struct failtest_call *, unsigned);
23 static int tracefd = -1;
25 unsigned int failtest_timeout_ms = 20000;
28 const char *debugpath;
40 /* end is inclusive: you can't have a 0-byte lock. */
45 bool (*failtest_exit_check)(struct failtest_call *history, unsigned num);
47 static struct failtest_call *history = NULL;
48 static unsigned int history_num = 0;
49 static int control_fd = -1;
50 static struct timeval start;
51 static unsigned int probe_count = 0;
53 static struct write_call *child_writes = NULL;
54 static unsigned int child_writes_num = 0;
56 static pid_t lock_owner;
57 static struct lock_info *locks = NULL;
58 static unsigned int lock_num = 0;
60 static const char info_to_arg[] = "mceoxprwf";
62 /* Dummy call used for failtest_undo wrappers. */
63 static struct failtest_call unrecorded_call;
65 static struct failtest_call *add_history_(enum failtest_call_type type,
71 /* NULL file is how we suppress failure. */
73 return &unrecorded_call;
75 history = realloc(history, (history_num + 1) * sizeof(*history));
76 history[history_num].type = type;
77 history[history_num].file = file;
78 history[history_num].line = line;
79 history[history_num].cleanup = NULL;
80 memcpy(&history[history_num].u, elem, elem_size);
81 return &history[history_num++];
84 #define add_history(type, file, line, elem) \
85 add_history_((type), (file), (line), (elem), sizeof(*(elem)))
87 #define set_cleanup(call, clean, type) \
88 (call)->cleanup = (void *)((void)sizeof(clean((type *)NULL)), (clean))
90 static bool read_write_info(int fd)
95 /* We don't need all of this, but it's simple. */
96 child_writes = realloc(child_writes,
97 (child_writes_num+1) * sizeof(child_writes[0]));
98 w = &child_writes[child_writes_num];
99 if (!read_all(fd, w, sizeof(*w)))
102 w->buf = buf = malloc(w->count);
103 if (!read_all(fd, buf, w->count))
110 static char *failpath_string(void)
113 char *ret = malloc(history_num + 1);
115 for (i = 0; i < history_num; i++) {
116 ret[i] = info_to_arg[history[i].type];
118 ret[i] = toupper(ret[i]);
124 static void tell_parent(enum info_type type)
126 if (control_fd != -1)
127 write_all(control_fd, &type, sizeof(type));
130 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
133 char *path = failpath_string();
136 vfprintf(stderr, fmt, ap);
139 fprintf(stderr, "%.*s", (int)outlen, out);
140 printf("To reproduce: --failpath=%s\n", path);
142 tell_parent(FAILURE);
146 static void trace(const char *fmt, ...)
154 vdprintf(tracefd, fmt, ap);
160 static void hand_down(int signum)
165 static void release_locks(void)
167 /* Locks were never acquired/reacquired? */
171 /* We own them? Release them all. */
172 if (lock_owner == getpid()) {
176 fl.l_whence = SEEK_SET;
180 for (i = 0; i < lock_num; i++)
181 fcntl(locks[i].fd, F_SETLK, &fl);
183 /* Our parent must have them; pass request up. */
184 enum info_type type = RELEASE_LOCKS;
185 assert(control_fd != -1);
186 write_all(control_fd, &type, sizeof(type));
191 /* off_t is a signed type. Getting its max is non-trivial. */
192 static off_t off_max(void)
194 BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
195 if (sizeof(off_t) == 4)
196 return (off_t)0x7FFFFFF;
198 return (off_t)0x7FFFFFFFFFFFFFFULL;
201 static void get_locks(void)
206 if (lock_owner == getpid())
209 if (lock_owner != 0) {
210 enum info_type type = RELEASE_LOCKS;
211 assert(control_fd != -1);
212 write_all(control_fd, &type, sizeof(type));
215 fl.l_whence = SEEK_SET;
217 for (i = 0; i < lock_num; i++) {
218 fl.l_type = locks[i].type;
219 fl.l_start = locks[i].start;
220 if (locks[i].end == off_max())
223 fl.l_len = locks[i].end - locks[i].start + 1;
225 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
228 lock_owner = getpid();
232 struct saved_file *next;
238 static struct saved_file *save_file(struct saved_file *next, int fd)
240 struct saved_file *s = malloc(sizeof(*s));
244 s->off = lseek(fd, 0, SEEK_CUR);
245 /* Special file? Erk... */
246 assert(s->off != -1);
247 s->len = lseek(fd, 0, SEEK_END);
248 lseek(fd, 0, SEEK_SET);
249 s->contents = malloc(s->len);
250 read(fd, s->contents, s->len);
251 lseek(fd, s->off, SEEK_SET);
255 /* We have little choice but to save and restore open files: mmap means we
256 * can really intercept changes in the child.
258 * We could do non-mmap'ed files on demand, however. */
259 static struct saved_file *save_files(void)
261 struct saved_file *files = NULL;
264 /* Figure out the set of live fds. */
265 for (i = history_num - 2; i >= 0; i--) {
266 if (history[i].type == FAILTEST_OPEN) {
267 int fd = history[i].u.open.ret;
268 /* Only do successful, writable fds. */
272 /* If it was closed, cleanup == NULL. */
273 if (!history[i].cleanup)
276 if ((history[i].u.open.flags & O_RDWR) == O_RDWR) {
277 files = save_file(files, fd);
278 } else if ((history[i].u.open.flags & O_WRONLY)
280 /* FIXME: Handle O_WRONLY. Open with O_RDWR? */
289 static void restore_files(struct saved_file *s)
292 struct saved_file *next = s->next;
294 lseek(s->fd, 0, SEEK_SET);
295 write(s->fd, s->contents, s->len);
296 ftruncate(s->fd, s->len);
298 lseek(s->fd, s->off, SEEK_SET);
304 /* Free up memory, so valgrind doesn't report leaks. */
305 static void free_everything(void)
309 /* We don't do this in cleanup: needed even for failed opens. */
310 for (i = 0; i < history_num; i++) {
311 if (history[i].type == FAILTEST_OPEN)
312 free((char *)history[i].u.open.pathname);
317 static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
321 /* For children, we don't care if they "failed" the testing. */
322 if (control_fd != -1)
328 /* Cleanup everything, in reverse order. */
329 for (i = history_num - 1; i >= 0; i--) {
330 if (!history[i].cleanup)
332 if (!forced_cleanup) {
333 printf("Leak at %s:%u: --failpath=%s\n",
334 history[i].file, history[i].line,
338 history[i].cleanup(&history[i].u);
342 tell_parent(SUCCESS);
346 static bool should_fail(struct failtest_call *call)
349 int control[2], output[2];
350 enum info_type type = UNEXPECTED;
353 struct saved_file *files;
355 /* Are we probing? */
356 if (probe_count && --probe_count == 0)
357 failtest_cleanup(true, 0);
359 if (call == &unrecorded_call)
363 /* + means continue after end, like normal. */
364 if (*failpath == '+')
367 if (tolower((unsigned char)*failpath)
368 != info_to_arg[call->type])
369 errx(1, "Failpath expected '%c' got '%c'\n",
370 info_to_arg[call->type], *failpath);
371 call->fail = isupper((unsigned char)*(failpath++));
376 /* Attach debugger if they asked for it. */
377 if (debugpath && history_num == strlen(debugpath)) {
380 for (i = 0; i < history_num; i++) {
381 unsigned char c = info_to_arg[history[i].type];
384 if (c != debugpath[i])
387 if (i == history_num) {
391 signal(SIGUSR1, SIG_IGN);
392 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
400 switch (failtest_hook(history, history_num)) {
407 /* Already down probe path? Stop now. */
409 failtest_cleanup(true, 0);
410 /* FIXME: We should run *parent* and run probe until
411 * calls match up again. */
419 files = save_files();
421 /* We're going to fail in the child. */
423 if (pipe(control) != 0 || pipe(output) != 0)
424 err(1, "opening pipe");
426 /* Prevent double-printing (in child and parent) */
430 err(1, "forking failed");
436 gettimeofday(&now, NULL);
437 if (now.tv_usec < start.tv_usec) {
439 now.tv_usec += 1000000;
441 now.tv_usec -= start.tv_usec;
442 now.tv_sec -= start.tv_sec;
443 p = failpath_string();
444 trace("%u->%u (%u.%02u): %s (", getppid(), getpid(),
445 (int)now.tv_sec, (int)now.tv_usec / 10000, p);
447 p = strrchr(history[history_num-1].file, '/');
451 trace("%s", history[history_num-1].file);
452 trace(":%u)\n", history[history_num-1].line);
456 dup2(output[1], STDOUT_FILENO);
457 dup2(output[1], STDERR_FILENO);
458 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
460 control_fd = control[1];
464 signal(SIGUSR1, hand_down);
469 /* We grab output so we can display it; we grab writes so we
472 struct pollfd pfd[2];
475 pfd[0].fd = output[0];
476 pfd[0].events = POLLIN|POLLHUP;
477 pfd[1].fd = control[0];
478 pfd[1].events = POLLIN|POLLHUP;
481 ret = poll(pfd, 1, failtest_timeout_ms);
483 ret = poll(pfd, 2, failtest_timeout_ms);
488 if (pfd[0].revents & POLLIN) {
491 out = realloc(out, outlen + 8192);
492 len = read(output[0], out + outlen, 8192);
494 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
495 if (read_all(control[0], &type, sizeof(type))) {
497 if (!read_write_info(control[0]))
499 } else if (type == RELEASE_LOCKS) {
501 /* FIXME: Tell them we're done... */
504 } else if (pfd[0].revents & POLLHUP) {
507 } while (type != FAILURE);
511 waitpid(child, &status, 0);
512 if (!WIFEXITED(status)) {
513 if (WTERMSIG(status) == SIGUSR1)
514 child_fail(out, outlen, "Timed out");
516 child_fail(out, outlen, "Killed by signal %u: ",
519 /* Child printed failure already, just pass up exit code. */
520 if (type == FAILURE) {
521 fprintf(stderr, "%.*s", (int)outlen, out);
523 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
525 if (WEXITSTATUS(status) != 0)
526 child_fail(out, outlen, "Exited with status %i: ",
527 WEXITSTATUS(status));
530 signal(SIGUSR1, SIG_DFL);
532 restore_files(files);
534 /* We continue onwards without failing. */
539 static void cleanup_calloc(struct calloc_call *call)
544 void *failtest_calloc(size_t nmemb, size_t size,
545 const char *file, unsigned line)
547 struct failtest_call *p;
548 struct calloc_call call;
551 p = add_history(FAILTEST_CALLOC, file, line, &call);
553 if (should_fail(p)) {
554 p->u.calloc.ret = NULL;
557 p->u.calloc.ret = calloc(nmemb, size);
558 set_cleanup(p, cleanup_calloc, struct calloc_call);
561 return p->u.calloc.ret;
564 static void cleanup_malloc(struct malloc_call *call)
569 void *failtest_malloc(size_t size, const char *file, unsigned line)
571 struct failtest_call *p;
572 struct malloc_call call;
575 p = add_history(FAILTEST_MALLOC, file, line, &call);
576 if (should_fail(p)) {
577 p->u.calloc.ret = NULL;
580 p->u.calloc.ret = malloc(size);
581 set_cleanup(p, cleanup_malloc, struct malloc_call);
584 return p->u.calloc.ret;
587 static void cleanup_realloc(struct realloc_call *call)
592 /* Walk back and find out if we got this ptr from a previous routine. */
593 static void fixup_ptr_history(void *ptr, unsigned int last)
597 /* Start at end of history, work back. */
598 for (i = last - 1; i >= 0; i--) {
599 switch (history[i].type) {
600 case FAILTEST_REALLOC:
601 if (history[i].u.realloc.ret == ptr) {
602 history[i].cleanup = NULL;
606 case FAILTEST_MALLOC:
607 if (history[i].u.malloc.ret == ptr) {
608 history[i].cleanup = NULL;
612 case FAILTEST_CALLOC:
613 if (history[i].u.calloc.ret == ptr) {
614 history[i].cleanup = NULL;
624 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
626 struct failtest_call *p;
627 struct realloc_call call;
629 p = add_history(FAILTEST_REALLOC, file, line, &call);
631 /* FIXME: Try one child moving allocation, one not. */
632 if (should_fail(p)) {
633 p->u.realloc.ret = NULL;
636 fixup_ptr_history(ptr, history_num-1);
637 p->u.realloc.ret = realloc(ptr, size);
638 set_cleanup(p, cleanup_realloc, struct realloc_call);
641 return p->u.realloc.ret;
644 void failtest_free(void *ptr)
646 fixup_ptr_history(ptr, history_num);
650 static void cleanup_open(struct open_call *call)
655 int failtest_open(const char *pathname,
656 const char *file, unsigned line, ...)
658 struct failtest_call *p;
659 struct open_call call;
662 call.pathname = strdup(pathname);
664 call.flags = va_arg(ap, int);
665 if (call.flags & O_CREAT) {
666 call.mode = va_arg(ap, mode_t);
669 p = add_history(FAILTEST_OPEN, file, line, &call);
670 /* Avoid memory leak! */
671 if (p == &unrecorded_call)
672 free((char *)call.pathname);
673 p->u.open.ret = open(pathname, call.flags, call.mode);
675 if (!failpath && p->u.open.ret == -1) {
678 } else if (should_fail(p)) {
679 close(p->u.open.ret);
681 /* FIXME: Play with error codes? */
684 set_cleanup(p, cleanup_open, struct open_call);
687 return p->u.open.ret;
690 static void cleanup_pipe(struct pipe_call *call)
692 if (!call->closed[0])
694 if (!call->closed[1])
698 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
700 struct failtest_call *p;
701 struct pipe_call call;
703 p = add_history(FAILTEST_PIPE, file, line, &call);
704 if (should_fail(p)) {
706 /* FIXME: Play with error codes? */
709 p->u.pipe.ret = pipe(p->u.pipe.fds);
710 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
711 set_cleanup(p, cleanup_pipe, struct pipe_call);
713 /* This causes valgrind to notice if they use pipefd[] after failure */
714 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
716 return p->u.pipe.ret;
719 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
720 const char *file, unsigned line)
722 struct failtest_call *p;
723 struct read_call call;
728 p = add_history(FAILTEST_READ, file, line, &call);
730 /* FIXME: Try partial read returns. */
731 if (should_fail(p)) {
735 p->u.read.ret = pread(fd, buf, count, off);
738 return p->u.read.ret;
741 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
742 const char *file, unsigned line)
744 struct failtest_call *p;
745 struct write_call call;
751 p = add_history(FAILTEST_WRITE, file, line, &call);
753 /* If we're a child, we need to make sure we write the same thing
754 * to non-files as the parent does, so tell it. */
755 if (control_fd != -1 && off == (off_t)-1) {
756 enum info_type type = WRITE;
758 write_all(control_fd, &type, sizeof(type));
759 write_all(control_fd, &p->u.write, sizeof(p->u.write));
760 write_all(control_fd, buf, count);
763 /* FIXME: Try partial write returns. */
764 if (should_fail(p)) {
768 /* FIXME: We assume same write order in parent and child */
769 if (off == (off_t)-1 && child_writes_num != 0) {
770 if (child_writes[0].fd != fd)
771 errx(1, "Child wrote to fd %u, not %u?",
772 child_writes[0].fd, fd);
773 if (child_writes[0].off != p->u.write.off)
774 errx(1, "Child wrote to offset %zu, not %zu?",
775 (size_t)child_writes[0].off,
776 (size_t)p->u.write.off);
777 if (child_writes[0].count != count)
778 errx(1, "Child wrote length %zu, not %zu?",
779 child_writes[0].count, count);
780 if (memcmp(child_writes[0].buf, buf, count)) {
782 "Child wrote differently to"
783 " fd %u than we did!\n", fd);
785 free((char *)child_writes[0].buf);
787 memmove(&child_writes[0], &child_writes[1],
788 sizeof(child_writes[0]) * child_writes_num);
790 /* Is this is a socket or pipe, child wrote it
792 if (p->u.write.off == (off_t)-1) {
793 p->u.write.ret = count;
795 return p->u.write.ret;
798 p->u.write.ret = pwrite(fd, buf, count, off);
801 return p->u.write.ret;
804 ssize_t failtest_read(int fd, void *buf, size_t count,
805 const char *file, unsigned line)
807 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
811 ssize_t failtest_write(int fd, const void *buf, size_t count,
812 const char *file, unsigned line)
814 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
818 static struct lock_info *WARN_UNUSED_RESULT
819 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
824 for (i = 0; i < lock_num; i++) {
829 /* Four cases we care about:
843 if (start > l->start && end < l->end) {
844 /* Mid overlap: trim entry, add new one. */
845 off_t new_start, new_end;
849 locks = add_lock(locks,
850 fd, new_start, new_end, l->type);
852 } else if (start <= l->start && end >= l->end) {
853 /* Total overlap: eliminate entry. */
856 } else if (end >= l->start && end < l->end) {
857 /* Start overlap: trim entry. */
859 } else if (start > l->start && start <= l->end) {
860 /* End overlap: trim entry. */
863 /* Nothing left? Remove it. */
864 if (l->end < l->start) {
865 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
870 if (type != F_UNLCK) {
871 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
872 l = &locks[lock_num++];
881 /* We trap this so we can record it: we don't fail it. */
882 int failtest_close(int fd, const char *file, unsigned line)
885 struct close_call call;
886 struct failtest_call *p;
889 p = add_history(FAILTEST_CLOSE, file, line, &call);
892 /* Consume close from failpath. */
900 /* Trace history to find source of fd. */
901 for (i = history_num-1; i >= 0; i--) {
902 switch (history[i].type) {
905 if (history[i].u.pipe.fds[0] == fd) {
906 assert(!history[i].u.pipe.closed[0]);
907 history[i].u.pipe.closed[0] = true;
908 if (history[i].u.pipe.closed[1])
909 history[i].cleanup = NULL;
912 if (history[i].u.pipe.fds[1] == fd) {
913 assert(!history[i].u.pipe.closed[1]);
914 history[i].u.pipe.closed[1] = true;
915 if (history[i].u.pipe.closed[0])
916 history[i].cleanup = NULL;
921 if (history[i].u.open.ret == fd) {
922 assert((void *)history[i].cleanup
923 == (void *)cleanup_open);
924 history[i].cleanup = NULL;
934 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
938 /* Zero length means "to end of file" */
939 static off_t end_of(off_t start, off_t len)
943 return start + len - 1;
946 /* FIXME: This only handles locks, really. */
947 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
949 struct failtest_call *p;
950 struct fcntl_call call;
956 /* Argument extraction. */
961 call.arg.l = va_arg(ap, long);
963 return fcntl(fd, cmd, call.arg.l);
966 return fcntl(fd, cmd);
970 call.arg.fl = *va_arg(ap, struct flock *);
972 return fcntl(fd, cmd, &call.arg.fl);
976 call.arg.fl = *va_arg(ap, struct flock *);
980 /* This means you need to implement it here. */
981 err(1, "failtest: unknown fcntl %u", cmd);
984 p = add_history(FAILTEST_FCNTL, file, line, &call);
986 if (should_fail(p)) {
988 if (p->u.fcntl.cmd == F_SETLK)
994 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
996 if (p->u.fcntl.ret == -1)
999 /* We don't handle anything else yet. */
1000 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1001 locks = add_lock(locks,
1003 p->u.fcntl.arg.fl.l_start,
1004 end_of(p->u.fcntl.arg.fl.l_start,
1005 p->u.fcntl.arg.fl.l_len),
1006 p->u.fcntl.arg.fl.l_type);
1010 return p->u.fcntl.ret;
1013 void failtest_init(int argc, char *argv[])
1017 for (i = 1; i < argc; i++) {
1018 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1019 failpath = argv[i] + strlen("--failpath=");
1020 } else if (strcmp(argv[i], "--tracepath") == 0) {
1021 tracefd = dup(STDERR_FILENO);
1022 failtest_timeout_ms = -1;
1023 } else if (!strncmp(argv[i], "--debugpath=",
1024 strlen("--debugpath="))) {
1025 debugpath = argv[i] + strlen("--debugpath=");
1028 gettimeofday(&start, NULL);
1031 void failtest_exit(int status)
1033 if (failtest_exit_check) {
1034 if (!failtest_exit_check(history, history_num))
1035 child_fail(NULL, 0, "failtest_exit_check failed\n");
1038 failtest_cleanup(false, status);