1 /* Licensed under LGPL - see LICENSE file for details */
2 #include <ccan/failtest/failtest.h>
12 #include <sys/types.h>
18 #include <ccan/read_write_all/read_write_all.h>
19 #include <ccan/failtest/failtest_proto.h>
20 #include <ccan/build_assert/build_assert.h>
22 enum failtest_result (*failtest_hook)(struct failtest_call *, unsigned);
24 static int tracefd = -1;
26 unsigned int failtest_timeout_ms = 20000;
29 const char *debugpath;
41 /* end is inclusive: you can't have a 0-byte lock. */
46 bool (*failtest_exit_check)(struct failtest_call *history, unsigned num);
48 static struct failtest_call *history = NULL;
49 static unsigned int history_num = 0;
50 static int control_fd = -1;
51 static struct timeval start;
52 static unsigned int probe_count = 0;
54 static struct write_call *child_writes = NULL;
55 static unsigned int child_writes_num = 0;
57 static pid_t lock_owner;
58 static struct lock_info *locks = NULL;
59 static unsigned int lock_num = 0;
61 static pid_t orig_pid;
63 static const char info_to_arg[] = "mceoxprwf";
65 /* Dummy call used for failtest_undo wrappers. */
66 static struct failtest_call unrecorded_call;
68 static struct failtest_call *add_history_(enum failtest_call_type type,
74 /* NULL file is how we suppress failure. */
76 return &unrecorded_call;
78 history = realloc(history, (history_num + 1) * sizeof(*history));
79 history[history_num].type = type;
80 history[history_num].file = file;
81 history[history_num].line = line;
82 history[history_num].cleanup = NULL;
83 memcpy(&history[history_num].u, elem, elem_size);
84 return &history[history_num++];
87 #define add_history(type, file, line, elem) \
88 add_history_((type), (file), (line), (elem), sizeof(*(elem)))
90 /* We do a fake call inside a sizeof(), to check types. */
91 #define set_cleanup(call, clean, type) \
92 (call)->cleanup = (void *)((void)sizeof(clean((type *)NULL),1), (clean))
94 static bool read_write_info(int fd)
99 /* We don't need all of this, but it's simple. */
100 child_writes = realloc(child_writes,
101 (child_writes_num+1) * sizeof(child_writes[0]));
102 w = &child_writes[child_writes_num];
103 if (!read_all(fd, w, sizeof(*w)))
106 w->buf = buf = malloc(w->count);
107 if (!read_all(fd, buf, w->count))
114 static char *failpath_string(void)
117 char *ret = malloc(history_num + 1);
119 for (i = 0; i < history_num; i++) {
120 ret[i] = info_to_arg[history[i].type];
122 ret[i] = toupper(ret[i]);
128 static void tell_parent(enum info_type type)
130 if (control_fd != -1)
131 write_all(control_fd, &type, sizeof(type));
134 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
137 char *path = failpath_string();
140 vfprintf(stderr, fmt, ap);
143 fprintf(stderr, "%.*s", (int)outlen, out);
144 printf("To reproduce: --failpath=%s\n", path);
146 tell_parent(FAILURE);
150 static void trace(const char *fmt, ...)
158 vdprintf(tracefd, fmt, ap);
164 static void hand_down(int signum)
169 static void release_locks(void)
171 /* Locks were never acquired/reacquired? */
175 /* We own them? Release them all. */
176 if (lock_owner == getpid()) {
180 fl.l_whence = SEEK_SET;
184 for (i = 0; i < lock_num; i++)
185 fcntl(locks[i].fd, F_SETLK, &fl);
187 /* Our parent must have them; pass request up. */
188 enum info_type type = RELEASE_LOCKS;
189 assert(control_fd != -1);
190 write_all(control_fd, &type, sizeof(type));
195 /* off_t is a signed type. Getting its max is non-trivial. */
196 static off_t off_max(void)
198 BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
199 if (sizeof(off_t) == 4)
200 return (off_t)0x7FFFFFF;
202 return (off_t)0x7FFFFFFFFFFFFFFULL;
205 static void get_locks(void)
210 if (lock_owner == getpid())
213 if (lock_owner != 0) {
214 enum info_type type = RELEASE_LOCKS;
215 assert(control_fd != -1);
216 write_all(control_fd, &type, sizeof(type));
219 fl.l_whence = SEEK_SET;
221 for (i = 0; i < lock_num; i++) {
222 fl.l_type = locks[i].type;
223 fl.l_start = locks[i].start;
224 if (locks[i].end == off_max())
227 fl.l_len = locks[i].end - locks[i].start + 1;
229 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
232 lock_owner = getpid();
236 struct saved_file *next;
242 static struct saved_file *save_file(struct saved_file *next, int fd)
244 struct saved_file *s = malloc(sizeof(*s));
248 s->off = lseek(fd, 0, SEEK_CUR);
249 /* Special file? Erk... */
250 assert(s->off != -1);
251 s->len = lseek(fd, 0, SEEK_END);
252 lseek(fd, 0, SEEK_SET);
253 s->contents = malloc(s->len);
254 if (read(fd, s->contents, s->len) != s->len)
255 err(1, "Failed to save %zu bytes", (size_t)s->len);
256 lseek(fd, s->off, SEEK_SET);
260 /* We have little choice but to save and restore open files: mmap means we
261 * can really intercept changes in the child.
263 * We could do non-mmap'ed files on demand, however. */
264 static struct saved_file *save_files(void)
266 struct saved_file *files = NULL;
269 /* Figure out the set of live fds. */
270 for (i = history_num - 2; i >= 0; i--) {
271 if (history[i].type == FAILTEST_OPEN) {
272 int fd = history[i].u.open.ret;
273 /* Only do successful, writable fds. */
277 /* If it was closed, cleanup == NULL. */
278 if (!history[i].cleanup)
281 if ((history[i].u.open.flags & O_RDWR) == O_RDWR) {
282 files = save_file(files, fd);
283 } else if ((history[i].u.open.flags & O_WRONLY)
285 /* FIXME: Handle O_WRONLY. Open with O_RDWR? */
294 static void restore_files(struct saved_file *s)
297 struct saved_file *next = s->next;
299 lseek(s->fd, 0, SEEK_SET);
300 if (write(s->fd, s->contents, s->len) != s->len)
301 err(1, "Failed to restore %zu bytes", (size_t)s->len);
302 if (ftruncate(s->fd, s->len) != 0)
303 err(1, "Failed to trim file to length %zu",
306 lseek(s->fd, s->off, SEEK_SET);
312 static void free_files(struct saved_file *s)
315 struct saved_file *next = s->next;
322 /* Free up memory, so valgrind doesn't report leaks. */
323 static void free_everything(void)
327 /* We don't do this in cleanup: needed even for failed opens. */
328 for (i = 0; i < history_num; i++) {
329 if (history[i].type == FAILTEST_OPEN)
330 free((char *)history[i].u.open.pathname);
335 static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
339 /* For children, we don't care if they "failed" the testing. */
340 if (control_fd != -1)
346 /* Cleanup everything, in reverse order. */
347 for (i = history_num - 1; i >= 0; i--) {
348 if (!history[i].cleanup)
350 if (!forced_cleanup) {
351 printf("Leak at %s:%u: --failpath=%s\n",
352 history[i].file, history[i].line,
356 history[i].cleanup(&history[i].u);
360 tell_parent(SUCCESS);
364 static bool should_fail(struct failtest_call *call)
367 int control[2], output[2];
368 enum info_type type = UNEXPECTED;
371 struct saved_file *files;
373 /* Are we probing? */
374 if (probe_count && --probe_count == 0 && control_fd != -1)
375 failtest_cleanup(true, 0);
377 if (call == &unrecorded_call)
381 /* + means continue after end, like normal. */
382 if (*failpath == '+')
384 else if (*failpath == '\0') {
385 /* Continue, but don't inject errors. */
386 return call->fail = false;
388 if (tolower((unsigned char)*failpath)
389 != info_to_arg[call->type])
390 errx(1, "Failpath expected '%c' got '%c'\n",
391 info_to_arg[call->type], *failpath);
392 call->fail = isupper((unsigned char)*(failpath++));
397 /* Attach debugger if they asked for it. */
398 if (debugpath && history_num == strlen(debugpath)) {
401 for (i = 0; i < history_num; i++) {
402 unsigned char c = info_to_arg[history[i].type];
405 if (c != debugpath[i])
408 if (i == history_num) {
412 signal(SIGUSR1, SIG_IGN);
413 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
415 if (system(str) == 0)
421 switch (failtest_hook(history, history_num)) {
425 /* Already down probe path? Stop now. */
427 /* FIXME: We should run *parent* and
428 * run probe until calls match up again. */
432 /* Child should give up now. */
433 if (control_fd != -1)
434 failtest_cleanup(true, 0);
435 /* Parent, don't fail again. */
445 files = save_files();
447 /* We're going to fail in the child. */
449 if (pipe(control) != 0 || pipe(output) != 0)
450 err(1, "opening pipe");
452 /* Prevent double-printing (in child and parent) */
456 err(1, "forking failed");
462 gettimeofday(&now, NULL);
463 if (now.tv_usec < start.tv_usec) {
465 now.tv_usec += 1000000;
467 now.tv_usec -= start.tv_usec;
468 now.tv_sec -= start.tv_sec;
469 p = failpath_string();
470 trace("%u->%u (%u.%02u): %s (", getppid(), getpid(),
471 (int)now.tv_sec, (int)now.tv_usec / 10000, p);
473 p = strrchr(history[history_num-1].file, '/');
477 trace("%s", history[history_num-1].file);
478 trace(":%u)\n", history[history_num-1].line);
482 dup2(output[1], STDOUT_FILENO);
483 dup2(output[1], STDERR_FILENO);
484 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
486 control_fd = control[1];
487 /* Valgrind spots the leak if we don't free these. */
492 signal(SIGUSR1, hand_down);
497 /* We grab output so we can display it; we grab writes so we
500 struct pollfd pfd[2];
503 pfd[0].fd = output[0];
504 pfd[0].events = POLLIN|POLLHUP;
505 pfd[1].fd = control[0];
506 pfd[1].events = POLLIN|POLLHUP;
509 ret = poll(pfd, 1, failtest_timeout_ms);
511 ret = poll(pfd, 2, failtest_timeout_ms);
518 err(1, "Poll returned %i", ret);
521 if (pfd[0].revents & POLLIN) {
524 out = realloc(out, outlen + 8192);
525 len = read(output[0], out + outlen, 8192);
527 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
528 if (read_all(control[0], &type, sizeof(type))) {
530 if (!read_write_info(control[0]))
532 } else if (type == RELEASE_LOCKS) {
534 /* FIXME: Tell them we're done... */
537 } else if (pfd[0].revents & POLLHUP) {
540 } while (type != FAILURE);
544 waitpid(child, &status, 0);
545 if (!WIFEXITED(status)) {
546 if (WTERMSIG(status) == SIGUSR1)
547 child_fail(out, outlen, "Timed out");
549 child_fail(out, outlen, "Killed by signal %u: ",
552 /* Child printed failure already, just pass up exit code. */
553 if (type == FAILURE) {
554 fprintf(stderr, "%.*s", (int)outlen, out);
556 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
558 if (WEXITSTATUS(status) != 0)
559 child_fail(out, outlen, "Exited with status %i: ",
560 WEXITSTATUS(status));
563 signal(SIGUSR1, SIG_DFL);
565 restore_files(files);
567 /* We continue onwards without failing. */
572 static void cleanup_calloc(struct calloc_call *call)
577 void *failtest_calloc(size_t nmemb, size_t size,
578 const char *file, unsigned line)
580 struct failtest_call *p;
581 struct calloc_call call;
584 p = add_history(FAILTEST_CALLOC, file, line, &call);
586 if (should_fail(p)) {
587 p->u.calloc.ret = NULL;
590 p->u.calloc.ret = calloc(nmemb, size);
591 set_cleanup(p, cleanup_calloc, struct calloc_call);
594 return p->u.calloc.ret;
597 static void cleanup_malloc(struct malloc_call *call)
602 void *failtest_malloc(size_t size, const char *file, unsigned line)
604 struct failtest_call *p;
605 struct malloc_call call;
608 p = add_history(FAILTEST_MALLOC, file, line, &call);
609 if (should_fail(p)) {
610 p->u.calloc.ret = NULL;
613 p->u.calloc.ret = malloc(size);
614 set_cleanup(p, cleanup_malloc, struct malloc_call);
617 return p->u.calloc.ret;
620 static void cleanup_realloc(struct realloc_call *call)
625 /* Walk back and find out if we got this ptr from a previous routine. */
626 static void fixup_ptr_history(void *ptr, unsigned int last)
630 /* Start at end of history, work back. */
631 for (i = last - 1; i >= 0; i--) {
632 switch (history[i].type) {
633 case FAILTEST_REALLOC:
634 if (history[i].u.realloc.ret == ptr) {
635 history[i].cleanup = NULL;
639 case FAILTEST_MALLOC:
640 if (history[i].u.malloc.ret == ptr) {
641 history[i].cleanup = NULL;
645 case FAILTEST_CALLOC:
646 if (history[i].u.calloc.ret == ptr) {
647 history[i].cleanup = NULL;
657 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
659 struct failtest_call *p;
660 struct realloc_call call;
662 p = add_history(FAILTEST_REALLOC, file, line, &call);
664 /* FIXME: Try one child moving allocation, one not. */
665 if (should_fail(p)) {
666 p->u.realloc.ret = NULL;
669 fixup_ptr_history(ptr, history_num-1);
670 p->u.realloc.ret = realloc(ptr, size);
671 set_cleanup(p, cleanup_realloc, struct realloc_call);
674 return p->u.realloc.ret;
677 void failtest_free(void *ptr)
679 fixup_ptr_history(ptr, history_num);
683 static void cleanup_open(struct open_call *call)
688 int failtest_open(const char *pathname,
689 const char *file, unsigned line, ...)
691 struct failtest_call *p;
692 struct open_call call;
695 call.pathname = strdup(pathname);
697 call.flags = va_arg(ap, int);
698 if (call.flags & O_CREAT) {
699 call.mode = va_arg(ap, int);
702 p = add_history(FAILTEST_OPEN, file, line, &call);
703 /* Avoid memory leak! */
704 if (p == &unrecorded_call)
705 free((char *)call.pathname);
706 p->u.open.ret = open(pathname, call.flags, call.mode);
708 if (!failpath && p->u.open.ret == -1) {
711 } else if (should_fail(p)) {
712 close(p->u.open.ret);
714 /* FIXME: Play with error codes? */
717 set_cleanup(p, cleanup_open, struct open_call);
720 return p->u.open.ret;
723 static void cleanup_pipe(struct pipe_call *call)
725 if (!call->closed[0])
727 if (!call->closed[1])
731 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
733 struct failtest_call *p;
734 struct pipe_call call;
736 p = add_history(FAILTEST_PIPE, file, line, &call);
737 if (should_fail(p)) {
739 /* FIXME: Play with error codes? */
742 p->u.pipe.ret = pipe(p->u.pipe.fds);
743 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
744 set_cleanup(p, cleanup_pipe, struct pipe_call);
746 /* This causes valgrind to notice if they use pipefd[] after failure */
747 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
749 return p->u.pipe.ret;
752 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
753 const char *file, unsigned line)
755 struct failtest_call *p;
756 struct read_call call;
761 p = add_history(FAILTEST_READ, file, line, &call);
763 /* FIXME: Try partial read returns. */
764 if (should_fail(p)) {
768 p->u.read.ret = pread(fd, buf, count, off);
771 return p->u.read.ret;
774 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
775 const char *file, unsigned line)
777 struct failtest_call *p;
778 struct write_call call;
784 p = add_history(FAILTEST_WRITE, file, line, &call);
786 /* If we're a child, we need to make sure we write the same thing
787 * to non-files as the parent does, so tell it. */
788 if (control_fd != -1 && off == (off_t)-1) {
789 enum info_type type = WRITE;
791 write_all(control_fd, &type, sizeof(type));
792 write_all(control_fd, &p->u.write, sizeof(p->u.write));
793 write_all(control_fd, buf, count);
796 /* FIXME: Try partial write returns. */
797 if (should_fail(p)) {
801 /* FIXME: We assume same write order in parent and child */
802 if (off == (off_t)-1 && child_writes_num != 0) {
803 if (child_writes[0].fd != fd)
804 errx(1, "Child wrote to fd %u, not %u?",
805 child_writes[0].fd, fd);
806 if (child_writes[0].off != p->u.write.off)
807 errx(1, "Child wrote to offset %zu, not %zu?",
808 (size_t)child_writes[0].off,
809 (size_t)p->u.write.off);
810 if (child_writes[0].count != count)
811 errx(1, "Child wrote length %zu, not %zu?",
812 child_writes[0].count, count);
813 if (memcmp(child_writes[0].buf, buf, count)) {
815 "Child wrote differently to"
816 " fd %u than we did!\n", fd);
818 free((char *)child_writes[0].buf);
820 memmove(&child_writes[0], &child_writes[1],
821 sizeof(child_writes[0]) * child_writes_num);
823 /* Is this is a socket or pipe, child wrote it
825 if (p->u.write.off == (off_t)-1) {
826 p->u.write.ret = count;
828 return p->u.write.ret;
831 p->u.write.ret = pwrite(fd, buf, count, off);
834 return p->u.write.ret;
837 ssize_t failtest_read(int fd, void *buf, size_t count,
838 const char *file, unsigned line)
840 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
844 ssize_t failtest_write(int fd, const void *buf, size_t count,
845 const char *file, unsigned line)
847 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
851 static struct lock_info *WARN_UNUSED_RESULT
852 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
857 for (i = 0; i < lock_num; i++) {
862 /* Four cases we care about:
876 if (start > l->start && end < l->end) {
877 /* Mid overlap: trim entry, add new one. */
878 off_t new_start, new_end;
882 locks = add_lock(locks,
883 fd, new_start, new_end, l->type);
885 } else if (start <= l->start && end >= l->end) {
886 /* Total overlap: eliminate entry. */
889 } else if (end >= l->start && end < l->end) {
890 /* Start overlap: trim entry. */
892 } else if (start > l->start && start <= l->end) {
893 /* End overlap: trim entry. */
896 /* Nothing left? Remove it. */
897 if (l->end < l->start) {
898 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
903 if (type != F_UNLCK) {
904 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
905 l = &locks[lock_num++];
914 /* We trap this so we can record it: we don't fail it. */
915 int failtest_close(int fd, const char *file, unsigned line)
918 struct close_call call;
919 struct failtest_call *p;
922 p = add_history(FAILTEST_CLOSE, file, line, &call);
925 /* Consume close from failpath. */
933 /* Trace history to find source of fd. */
934 for (i = history_num-1; i >= 0; i--) {
935 switch (history[i].type) {
938 if (history[i].u.pipe.fds[0] == fd) {
939 assert(!history[i].u.pipe.closed[0]);
940 history[i].u.pipe.closed[0] = true;
941 if (history[i].u.pipe.closed[1])
942 history[i].cleanup = NULL;
945 if (history[i].u.pipe.fds[1] == fd) {
946 assert(!history[i].u.pipe.closed[1]);
947 history[i].u.pipe.closed[1] = true;
948 if (history[i].u.pipe.closed[0])
949 history[i].cleanup = NULL;
954 if (history[i].u.open.ret == fd) {
955 assert((void *)history[i].cleanup
956 == (void *)cleanup_open);
957 history[i].cleanup = NULL;
967 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
971 /* Zero length means "to end of file" */
972 static off_t end_of(off_t start, off_t len)
976 return start + len - 1;
979 /* FIXME: This only handles locks, really. */
980 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
982 struct failtest_call *p;
983 struct fcntl_call call;
989 /* Argument extraction. */
994 call.arg.l = va_arg(ap, long);
996 return fcntl(fd, cmd, call.arg.l);
999 return fcntl(fd, cmd);
1003 call.arg.fl = *va_arg(ap, struct flock *);
1005 return fcntl(fd, cmd, &call.arg.fl);
1009 call.arg.fl = *va_arg(ap, struct flock *);
1013 /* This means you need to implement it here. */
1014 err(1, "failtest: unknown fcntl %u", cmd);
1017 p = add_history(FAILTEST_FCNTL, file, line, &call);
1019 if (should_fail(p)) {
1020 p->u.fcntl.ret = -1;
1021 if (p->u.fcntl.cmd == F_SETLK)
1027 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
1028 &p->u.fcntl.arg.fl);
1029 if (p->u.fcntl.ret == -1)
1032 /* We don't handle anything else yet. */
1033 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1034 locks = add_lock(locks,
1036 p->u.fcntl.arg.fl.l_start,
1037 end_of(p->u.fcntl.arg.fl.l_start,
1038 p->u.fcntl.arg.fl.l_len),
1039 p->u.fcntl.arg.fl.l_type);
1043 return p->u.fcntl.ret;
1046 pid_t failtest_getpid(const char *file, unsigned line)
1048 /* You must call failtest_init first! */
1053 void failtest_init(int argc, char *argv[])
1057 orig_pid = getpid();
1059 for (i = 1; i < argc; i++) {
1060 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1061 failpath = argv[i] + strlen("--failpath=");
1062 } else if (strcmp(argv[i], "--tracepath") == 0) {
1063 tracefd = dup(STDERR_FILENO);
1064 failtest_timeout_ms = -1;
1065 } else if (!strncmp(argv[i], "--debugpath=",
1066 strlen("--debugpath="))) {
1067 debugpath = argv[i] + strlen("--debugpath=");
1070 gettimeofday(&start, NULL);
1073 bool failtest_has_failed(void)
1075 return control_fd != -1;
1078 void failtest_exit(int status)
1080 if (failtest_exit_check) {
1081 if (!failtest_exit_check(history, history_num))
1082 child_fail(NULL, 0, "failtest_exit_check failed\n");
1085 failtest_cleanup(false, status);