1 /* Licensed under LGPL - see LICENSE file for details */
2 #include <ccan/failtest/failtest.h>
12 #include <sys/types.h>
18 #include <ccan/time/time.h>
19 #include <ccan/read_write_all/read_write_all.h>
20 #include <ccan/failtest/failtest_proto.h>
21 #include <ccan/build_assert/build_assert.h>
22 #include <ccan/str/str.h>
24 enum failtest_result (*failtest_hook)(struct tlist_calls *);
26 static int tracefd = -1;
28 unsigned int failtest_timeout_ms = 20000;
31 const char *debugpath;
43 /* end is inclusive: you can't have a 0-byte lock. */
48 bool (*failtest_exit_check)(struct tlist_calls *history);
50 static struct tlist_calls history = TLIST_INIT(history);
51 static int control_fd = -1;
52 static struct timeval start;
53 static unsigned int probe_count = 0;
55 static struct write_call *child_writes = NULL;
56 static unsigned int child_writes_num = 0;
58 static pid_t lock_owner;
59 static struct lock_info *locks = NULL;
60 static unsigned int lock_num = 0;
62 static pid_t orig_pid;
64 static const char info_to_arg[] = "mceoxprwf";
66 /* Dummy call used for failtest_undo wrappers. */
67 static struct failtest_call unrecorded_call;
69 static struct failtest_call *add_history_(enum failtest_call_type type,
75 struct failtest_call *call;
77 /* NULL file is how we suppress failure. */
79 return &unrecorded_call;
81 call = malloc(sizeof *call);
86 memcpy(&call->u, elem, elem_size);
87 tlist_add_tail(&history, call, list);
91 #define add_history(type, file, line, elem) \
92 add_history_((type), (file), (line), (elem), sizeof(*(elem)))
94 /* We do a fake call inside a sizeof(), to check types. */
95 #define set_cleanup(call, clean, type) \
96 (call)->cleanup = (void *)((void)sizeof(clean((type *)NULL),1), (clean))
98 static bool read_write_info(int fd)
100 struct write_call *w;
103 /* We don't need all of this, but it's simple. */
104 child_writes = realloc(child_writes,
105 (child_writes_num+1) * sizeof(child_writes[0]));
106 w = &child_writes[child_writes_num];
107 if (!read_all(fd, w, sizeof(*w)))
110 w->buf = buf = malloc(w->count);
111 if (!read_all(fd, buf, w->count))
118 static char *failpath_string(void)
120 struct failtest_call *i;
121 char *ret = strdup("");
124 /* Inefficient, but who cares? */
125 tlist_for_each(&history, i, list) {
126 ret = realloc(ret, len + 2);
127 ret[len] = info_to_arg[i->type];
129 ret[len] = toupper(ret[len]);
135 static void tell_parent(enum info_type type)
137 if (control_fd != -1)
138 write_all(control_fd, &type, sizeof(type));
141 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
144 char *path = failpath_string();
147 vfprintf(stderr, fmt, ap);
150 fprintf(stderr, "%.*s", (int)outlen, out);
151 printf("To reproduce: --failpath=%s\n", path);
153 tell_parent(FAILURE);
157 static void trace(const char *fmt, ...)
165 vdprintf(tracefd, fmt, ap);
171 static void hand_down(int signum)
176 static void release_locks(void)
178 /* Locks were never acquired/reacquired? */
182 /* We own them? Release them all. */
183 if (lock_owner == getpid()) {
187 fl.l_whence = SEEK_SET;
191 for (i = 0; i < lock_num; i++)
192 fcntl(locks[i].fd, F_SETLK, &fl);
194 /* Our parent must have them; pass request up. */
195 enum info_type type = RELEASE_LOCKS;
196 assert(control_fd != -1);
197 write_all(control_fd, &type, sizeof(type));
202 /* off_t is a signed type. Getting its max is non-trivial. */
203 static off_t off_max(void)
205 BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
206 if (sizeof(off_t) == 4)
207 return (off_t)0x7FFFFFF;
209 return (off_t)0x7FFFFFFFFFFFFFFULL;
212 static void get_locks(void)
217 if (lock_owner == getpid())
220 if (lock_owner != 0) {
221 enum info_type type = RELEASE_LOCKS;
222 assert(control_fd != -1);
223 write_all(control_fd, &type, sizeof(type));
226 fl.l_whence = SEEK_SET;
228 for (i = 0; i < lock_num; i++) {
229 fl.l_type = locks[i].type;
230 fl.l_start = locks[i].start;
231 if (locks[i].end == off_max())
234 fl.l_len = locks[i].end - locks[i].start + 1;
236 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
239 lock_owner = getpid();
243 struct saved_file *next;
249 static struct saved_file *save_file(struct saved_file *next, int fd)
251 struct saved_file *s = malloc(sizeof(*s));
255 s->off = lseek(fd, 0, SEEK_CUR);
256 /* Special file? Erk... */
257 assert(s->off != -1);
258 s->len = lseek(fd, 0, SEEK_END);
259 lseek(fd, 0, SEEK_SET);
260 s->contents = malloc(s->len);
261 if (read(fd, s->contents, s->len) != s->len)
262 err(1, "Failed to save %zu bytes", (size_t)s->len);
263 lseek(fd, s->off, SEEK_SET);
267 /* We have little choice but to save and restore open files: mmap means we
268 * can really intercept changes in the child.
270 * We could do non-mmap'ed files on demand, however. */
271 static struct saved_file *save_files(void)
273 struct saved_file *files = NULL;
274 struct failtest_call *i;
276 /* Figure out the set of live fds. */
277 tlist_for_each_rev(&history, i, list) {
278 if (i->type == FAILTEST_OPEN) {
279 int fd = i->u.open.ret;
280 /* Only do successful, writable fds. */
284 /* If it was closed, cleanup == NULL. */
288 if ((i->u.open.flags & O_RDWR) == O_RDWR) {
289 files = save_file(files, fd);
290 } else if ((i->u.open.flags & O_WRONLY)
292 /* FIXME: Handle O_WRONLY. Open with O_RDWR? */
301 static void restore_files(struct saved_file *s)
304 struct saved_file *next = s->next;
306 lseek(s->fd, 0, SEEK_SET);
307 if (write(s->fd, s->contents, s->len) != s->len)
308 err(1, "Failed to restore %zu bytes", (size_t)s->len);
309 if (ftruncate(s->fd, s->len) != 0)
310 err(1, "Failed to trim file to length %zu",
313 lseek(s->fd, s->off, SEEK_SET);
319 static void free_files(struct saved_file *s)
322 struct saved_file *next = s->next;
329 static void free_call(struct failtest_call *call)
331 /* We don't do this in cleanup: needed even for failed opens. */
332 if (call->type == FAILTEST_OPEN)
333 free((char *)call->u.open.pathname);
334 tlist_del_from(&history, call, list);
338 /* Free up memory, so valgrind doesn't report leaks. */
339 static void free_everything(void)
341 struct failtest_call *i;
343 while ((i = tlist_top(&history, struct failtest_call, list)) != NULL)
347 static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
349 struct failtest_call *i;
351 /* For children, we don't care if they "failed" the testing. */
352 if (control_fd != -1)
355 if (forced_cleanup) {
356 /* We didn't actually do final operation: remove it. */
357 i = tlist_tail(&history, struct failtest_call, list);
361 /* Cleanup everything, in reverse order. */
362 tlist_for_each_rev(&history, i, list) {
365 if (!forced_cleanup) {
366 printf("Leak at %s:%u: --failpath=%s\n",
367 i->file, i->line, failpath_string());
374 tell_parent(SUCCESS);
378 static bool should_fail(struct failtest_call *call)
381 int control[2], output[2];
382 enum info_type type = UNEXPECTED;
385 struct saved_file *files;
387 /* Are we probing? */
388 if (probe_count && --probe_count == 0 && control_fd != -1)
389 failtest_cleanup(true, 0);
391 if (call == &unrecorded_call)
395 /* + means continue after end, like normal. */
396 if (*failpath == '+')
398 else if (*failpath == '\0') {
399 /* Continue, but don't inject errors. */
400 return call->fail = false;
402 if (tolower((unsigned char)*failpath)
403 != info_to_arg[call->type])
404 errx(1, "Failpath expected '%c' got '%c'\n",
405 info_to_arg[call->type], *failpath);
406 call->fail = cisupper(*(failpath++));
411 /* Attach debugger if they asked for it. */
413 char *path = failpath_string();
415 if (streq(path, debugpath)) {
419 signal(SIGUSR1, SIG_IGN);
420 sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
422 if (system(str) == 0)
424 } else if (!strstarts(path, debugpath)) {
425 fprintf(stderr, "--debugpath not followed: %s\n", path);
432 switch (failtest_hook(&history)) {
436 /* Already down probe path? Stop now. */
438 /* FIXME: We should run *parent* and
439 * run probe until calls match up again. */
443 /* Child should give up now. */
444 if (control_fd != -1)
445 failtest_cleanup(true, 0);
446 /* Parent, don't fail again. */
456 files = save_files();
458 /* We're going to fail in the child. */
460 if (pipe(control) != 0 || pipe(output) != 0)
461 err(1, "opening pipe");
463 /* Prevent double-printing (in child and parent) */
467 err(1, "forking failed");
474 struct failtest_call *c;
476 c = tlist_tail(&history, struct failtest_call, list);
477 diff = time_sub(time_now(), start);
478 failpath = failpath_string();
479 trace("%u->%u (%u.%02u): %s (", getppid(), getpid(),
480 (int)diff.tv_sec, (int)diff.tv_usec / 10000,
483 p = strrchr(c->file, '/');
487 trace("%s", c->file);
488 trace(":%u)\n", c->line);
492 dup2(output[1], STDOUT_FILENO);
493 dup2(output[1], STDERR_FILENO);
494 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
496 control_fd = control[1];
497 /* Valgrind spots the leak if we don't free these. */
502 signal(SIGUSR1, hand_down);
507 /* We grab output so we can display it; we grab writes so we
510 struct pollfd pfd[2];
513 pfd[0].fd = output[0];
514 pfd[0].events = POLLIN|POLLHUP;
515 pfd[1].fd = control[0];
516 pfd[1].events = POLLIN|POLLHUP;
519 ret = poll(pfd, 1, failtest_timeout_ms);
521 ret = poll(pfd, 2, failtest_timeout_ms);
528 err(1, "Poll returned %i", ret);
531 if (pfd[0].revents & POLLIN) {
534 out = realloc(out, outlen + 8192);
535 len = read(output[0], out + outlen, 8192);
537 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
538 if (read_all(control[0], &type, sizeof(type))) {
540 if (!read_write_info(control[0]))
542 } else if (type == RELEASE_LOCKS) {
544 /* FIXME: Tell them we're done... */
547 } else if (pfd[0].revents & POLLHUP) {
550 } while (type != FAILURE);
554 waitpid(child, &status, 0);
555 if (!WIFEXITED(status)) {
556 if (WTERMSIG(status) == SIGUSR1)
557 child_fail(out, outlen, "Timed out");
559 child_fail(out, outlen, "Killed by signal %u: ",
562 /* Child printed failure already, just pass up exit code. */
563 if (type == FAILURE) {
564 fprintf(stderr, "%.*s", (int)outlen, out);
566 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
568 if (WEXITSTATUS(status) != 0)
569 child_fail(out, outlen, "Exited with status %i: ",
570 WEXITSTATUS(status));
573 signal(SIGUSR1, SIG_DFL);
575 restore_files(files);
577 /* We continue onwards without failing. */
582 static void cleanup_calloc(struct calloc_call *call)
587 void *failtest_calloc(size_t nmemb, size_t size,
588 const char *file, unsigned line)
590 struct failtest_call *p;
591 struct calloc_call call;
594 p = add_history(FAILTEST_CALLOC, file, line, &call);
596 if (should_fail(p)) {
597 p->u.calloc.ret = NULL;
600 p->u.calloc.ret = calloc(nmemb, size);
601 set_cleanup(p, cleanup_calloc, struct calloc_call);
604 return p->u.calloc.ret;
607 static void cleanup_malloc(struct malloc_call *call)
612 void *failtest_malloc(size_t size, const char *file, unsigned line)
614 struct failtest_call *p;
615 struct malloc_call call;
618 p = add_history(FAILTEST_MALLOC, file, line, &call);
619 if (should_fail(p)) {
620 p->u.malloc.ret = NULL;
623 p->u.malloc.ret = malloc(size);
624 set_cleanup(p, cleanup_malloc, struct malloc_call);
627 return p->u.malloc.ret;
630 static void cleanup_realloc(struct realloc_call *call)
635 /* Walk back and find out if we got this ptr from a previous routine. */
636 static void fixup_ptr_history(void *ptr)
638 struct failtest_call *i;
640 /* Start at end of history, work back. */
641 tlist_for_each_rev(&history, i, list) {
643 case FAILTEST_REALLOC:
644 if (i->u.realloc.ret == ptr) {
649 case FAILTEST_MALLOC:
650 if (i->u.malloc.ret == ptr) {
655 case FAILTEST_CALLOC:
656 if (i->u.calloc.ret == ptr) {
667 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
669 struct failtest_call *p;
670 struct realloc_call call;
672 p = add_history(FAILTEST_REALLOC, file, line, &call);
674 /* FIXME: Try one child moving allocation, one not. */
675 if (should_fail(p)) {
676 p->u.realloc.ret = NULL;
679 /* Don't catch this one in the history fixup... */
680 p->u.realloc.ret = NULL;
681 fixup_ptr_history(ptr);
682 p->u.realloc.ret = realloc(ptr, size);
683 set_cleanup(p, cleanup_realloc, struct realloc_call);
686 return p->u.realloc.ret;
689 void failtest_free(void *ptr)
691 fixup_ptr_history(ptr);
695 static void cleanup_open(struct open_call *call)
700 int failtest_open(const char *pathname,
701 const char *file, unsigned line, ...)
703 struct failtest_call *p;
704 struct open_call call;
707 call.pathname = strdup(pathname);
709 call.flags = va_arg(ap, int);
710 if (call.flags & O_CREAT) {
711 call.mode = va_arg(ap, int);
714 p = add_history(FAILTEST_OPEN, file, line, &call);
715 /* Avoid memory leak! */
716 if (p == &unrecorded_call)
717 free((char *)call.pathname);
718 p->u.open.ret = open(pathname, call.flags, call.mode);
720 if (p->u.open.ret == -1) {
723 } else if (should_fail(p)) {
724 close(p->u.open.ret);
726 /* FIXME: Play with error codes? */
729 set_cleanup(p, cleanup_open, struct open_call);
732 return p->u.open.ret;
735 static void cleanup_pipe(struct pipe_call *call)
737 if (!call->closed[0])
739 if (!call->closed[1])
743 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
745 struct failtest_call *p;
746 struct pipe_call call;
748 p = add_history(FAILTEST_PIPE, file, line, &call);
749 if (should_fail(p)) {
751 /* FIXME: Play with error codes? */
754 p->u.pipe.ret = pipe(p->u.pipe.fds);
755 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
756 set_cleanup(p, cleanup_pipe, struct pipe_call);
758 /* This causes valgrind to notice if they use pipefd[] after failure */
759 memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
761 return p->u.pipe.ret;
764 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
765 const char *file, unsigned line)
767 struct failtest_call *p;
768 struct read_call call;
773 p = add_history(FAILTEST_READ, file, line, &call);
775 /* FIXME: Try partial read returns. */
776 if (should_fail(p)) {
780 p->u.read.ret = pread(fd, buf, count, off);
783 return p->u.read.ret;
786 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
787 const char *file, unsigned line)
789 struct failtest_call *p;
790 struct write_call call;
796 p = add_history(FAILTEST_WRITE, file, line, &call);
798 /* If we're a child, we need to make sure we write the same thing
799 * to non-files as the parent does, so tell it. */
800 if (control_fd != -1 && off == (off_t)-1) {
801 enum info_type type = WRITE;
803 write_all(control_fd, &type, sizeof(type));
804 write_all(control_fd, &p->u.write, sizeof(p->u.write));
805 write_all(control_fd, buf, count);
808 /* FIXME: Try partial write returns. */
809 if (should_fail(p)) {
813 /* FIXME: We assume same write order in parent and child */
814 if (off == (off_t)-1 && child_writes_num != 0) {
815 if (child_writes[0].fd != fd)
816 errx(1, "Child wrote to fd %u, not %u?",
817 child_writes[0].fd, fd);
818 if (child_writes[0].off != p->u.write.off)
819 errx(1, "Child wrote to offset %zu, not %zu?",
820 (size_t)child_writes[0].off,
821 (size_t)p->u.write.off);
822 if (child_writes[0].count != count)
823 errx(1, "Child wrote length %zu, not %zu?",
824 child_writes[0].count, count);
825 if (memcmp(child_writes[0].buf, buf, count)) {
827 "Child wrote differently to"
828 " fd %u than we did!\n", fd);
830 free((char *)child_writes[0].buf);
832 memmove(&child_writes[0], &child_writes[1],
833 sizeof(child_writes[0]) * child_writes_num);
835 /* Is this is a socket or pipe, child wrote it
837 if (p->u.write.off == (off_t)-1) {
838 p->u.write.ret = count;
840 return p->u.write.ret;
843 p->u.write.ret = pwrite(fd, buf, count, off);
846 return p->u.write.ret;
849 ssize_t failtest_read(int fd, void *buf, size_t count,
850 const char *file, unsigned line)
852 return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
856 ssize_t failtest_write(int fd, const void *buf, size_t count,
857 const char *file, unsigned line)
859 return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
863 static struct lock_info *WARN_UNUSED_RESULT
864 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
869 for (i = 0; i < lock_num; i++) {
874 /* Four cases we care about:
888 if (start > l->start && end < l->end) {
889 /* Mid overlap: trim entry, add new one. */
890 off_t new_start, new_end;
894 locks = add_lock(locks,
895 fd, new_start, new_end, l->type);
897 } else if (start <= l->start && end >= l->end) {
898 /* Total overlap: eliminate entry. */
901 } else if (end >= l->start && end < l->end) {
902 /* Start overlap: trim entry. */
904 } else if (start > l->start && start <= l->end) {
905 /* End overlap: trim entry. */
908 /* Nothing left? Remove it. */
909 if (l->end < l->start) {
910 memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
915 if (type != F_UNLCK) {
916 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
917 l = &locks[lock_num++];
926 /* We trap this so we can record it: we don't fail it. */
927 int failtest_close(int fd, const char *file, unsigned line)
929 struct failtest_call *i;
930 struct close_call call;
931 struct failtest_call *p;
934 p = add_history(FAILTEST_CLOSE, file, line, &call);
937 /* Consume close from failpath. */
945 /* Trace history to find source of fd. */
946 tlist_for_each_rev(&history, i, list) {
950 if (i->u.pipe.fds[0] == fd) {
951 assert(!i->u.pipe.closed[0]);
952 i->u.pipe.closed[0] = true;
953 if (i->u.pipe.closed[1])
957 if (i->u.pipe.fds[1] == fd) {
958 assert(!i->u.pipe.closed[1]);
959 i->u.pipe.closed[1] = true;
960 if (i->u.pipe.closed[0])
966 if (i->u.open.ret == fd) {
967 assert((void *)i->cleanup
968 == (void *)cleanup_open);
979 locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
983 /* Zero length means "to end of file" */
984 static off_t end_of(off_t start, off_t len)
988 return start + len - 1;
991 /* FIXME: This only handles locks, really. */
992 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
994 struct failtest_call *p;
995 struct fcntl_call call;
1001 /* Argument extraction. */
1006 call.arg.l = va_arg(ap, long);
1008 return fcntl(fd, cmd, call.arg.l);
1011 return fcntl(fd, cmd);
1015 call.arg.fl = *va_arg(ap, struct flock *);
1017 return fcntl(fd, cmd, &call.arg.fl);
1021 call.arg.fl = *va_arg(ap, struct flock *);
1025 /* This means you need to implement it here. */
1026 err(1, "failtest: unknown fcntl %u", cmd);
1029 p = add_history(FAILTEST_FCNTL, file, line, &call);
1031 if (should_fail(p)) {
1032 p->u.fcntl.ret = -1;
1033 if (p->u.fcntl.cmd == F_SETLK)
1039 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
1040 &p->u.fcntl.arg.fl);
1041 if (p->u.fcntl.ret == -1)
1044 /* We don't handle anything else yet. */
1045 assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1046 locks = add_lock(locks,
1048 p->u.fcntl.arg.fl.l_start,
1049 end_of(p->u.fcntl.arg.fl.l_start,
1050 p->u.fcntl.arg.fl.l_len),
1051 p->u.fcntl.arg.fl.l_type);
1055 return p->u.fcntl.ret;
1058 pid_t failtest_getpid(const char *file, unsigned line)
1060 /* You must call failtest_init first! */
1065 void failtest_init(int argc, char *argv[])
1069 orig_pid = getpid();
1071 for (i = 1; i < argc; i++) {
1072 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1073 failpath = argv[i] + strlen("--failpath=");
1074 } else if (strcmp(argv[i], "--tracepath") == 0) {
1075 tracefd = dup(STDERR_FILENO);
1076 failtest_timeout_ms = -1;
1077 } else if (!strncmp(argv[i], "--debugpath=",
1078 strlen("--debugpath="))) {
1079 debugpath = argv[i] + strlen("--debugpath=");
1085 bool failtest_has_failed(void)
1087 return control_fd != -1;
1090 void failtest_exit(int status)
1092 if (failtest_exit_check) {
1093 if (!failtest_exit_check(&history))
1094 child_fail(NULL, 0, "failtest_exit_check failed\n");
1097 failtest_cleanup(false, status);