]> git.ozlabs.org Git - ccan/blob - ccan/failtest/failtest.c
30903e3f3c4ecf232d474e2d09bc82f5238e777c
[ccan] / ccan / failtest / failtest.c
1 #include "config.h"
2 #include <stdarg.h>
3 #include <string.h>
4 #include <stdio.h>
5 #include <stdarg.h>
6 #include <ctype.h>
7 #include <err.h>
8 #include <unistd.h>
9 #include <poll.h>
10 #include <errno.h>
11 #include <sys/types.h>
12 #include <sys/wait.h>
13 #include <sys/stat.h>
14 #include <sys/time.h>
15 #include <assert.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>
20
21 enum failtest_result (*failtest_hook)(struct failtest_call *, unsigned);
22
23 static int tracefd = -1;
24
25 unsigned int failtest_timeout_ms = 20000;
26
27 const char *failpath;
28 const char *debugpath;
29
30 enum info_type {
31         WRITE,
32         RELEASE_LOCKS,
33         FAILURE,
34         SUCCESS,
35         UNEXPECTED
36 };
37
38 struct lock_info {
39         int fd;
40         /* end is inclusive: you can't have a 0-byte lock. */
41         off_t start, end;
42         int type;
43 };
44
45 bool (*failtest_exit_check)(struct failtest_call *history, unsigned num);
46
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;
52
53 static struct write_call *child_writes = NULL;
54 static unsigned int child_writes_num = 0;
55
56 static pid_t lock_owner;
57 static struct lock_info *locks = NULL;
58 static unsigned int lock_num = 0;
59
60 static const char info_to_arg[] = "mceoxprwf";
61
62 /* Dummy call used for failtest_undo wrappers. */
63 static struct failtest_call unrecorded_call;
64
65 static struct failtest_call *add_history_(enum failtest_call_type type,
66                                           const char *file,
67                                           unsigned int line,
68                                           const void *elem,
69                                           size_t elem_size)
70 {
71         /* NULL file is how we suppress failure. */
72         if (!file)
73                 return &unrecorded_call;
74
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++];
82 }
83
84 #define add_history(type, file, line, elem) \
85         add_history_((type), (file), (line), (elem), sizeof(*(elem)))
86
87 /* We do a fake call inside a sizeof(), to check types. */
88 #define set_cleanup(call, clean, type)                  \
89         (call)->cleanup = (void *)((void)sizeof(clean((type *)NULL),1), (clean))
90
91 static bool read_write_info(int fd)
92 {
93         struct write_call *w;
94         char *buf;
95
96         /* We don't need all of this, but it's simple. */
97         child_writes = realloc(child_writes,
98                                (child_writes_num+1) * sizeof(child_writes[0]));
99         w = &child_writes[child_writes_num];
100         if (!read_all(fd, w, sizeof(*w)))
101                 return false;
102
103         w->buf = buf = malloc(w->count);
104         if (!read_all(fd, buf, w->count))
105                 return false;
106
107         child_writes_num++;
108         return true;
109 }
110
111 static char *failpath_string(void)
112 {
113         unsigned int i;
114         char *ret = malloc(history_num + 1);
115
116         for (i = 0; i < history_num; i++) {
117                 ret[i] = info_to_arg[history[i].type];
118                 if (history[i].fail)
119                         ret[i] = toupper(ret[i]);
120         }
121         ret[i] = '\0';
122         return ret;
123 }
124
125 static void tell_parent(enum info_type type)
126 {
127         if (control_fd != -1)
128                 write_all(control_fd, &type, sizeof(type));
129 }
130
131 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
132 {
133         va_list ap;
134         char *path = failpath_string();
135
136         va_start(ap, fmt);
137         vfprintf(stderr, fmt, ap);
138         va_end(ap);
139
140         fprintf(stderr, "%.*s", (int)outlen, out);
141         printf("To reproduce: --failpath=%s\n", path);
142         free(path);
143         tell_parent(FAILURE);
144         exit(1);
145 }
146
147 static void trace(const char *fmt, ...)
148 {
149         va_list ap;
150
151         if (tracefd == -1)
152                 return;
153
154         va_start(ap, fmt);
155         vdprintf(tracefd, fmt, ap);
156         va_end(ap);
157 }
158
159 static pid_t child;
160
161 static void hand_down(int signum)
162 {
163         kill(child, signum);
164 }
165
166 static void release_locks(void)
167 {
168         /* Locks were never acquired/reacquired? */
169         if (lock_owner == 0)
170                 return;
171
172         /* We own them?  Release them all. */
173         if (lock_owner == getpid()) {
174                 unsigned int i;
175                 struct flock fl;
176                 fl.l_type = F_UNLCK;
177                 fl.l_whence = SEEK_SET;
178                 fl.l_start = 0;
179                 fl.l_len = 0;
180
181                 for (i = 0; i < lock_num; i++)
182                         fcntl(locks[i].fd, F_SETLK, &fl);
183         } else {
184                 /* Our parent must have them; pass request up. */
185                 enum info_type type = RELEASE_LOCKS;
186                 assert(control_fd != -1);
187                 write_all(control_fd, &type, sizeof(type));
188         }
189         lock_owner = 0;
190 }
191
192 /* off_t is a signed type.  Getting its max is non-trivial. */
193 static off_t off_max(void)
194 {
195         BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
196         if (sizeof(off_t) == 4)
197                 return (off_t)0x7FFFFFF;
198         else
199                 return (off_t)0x7FFFFFFFFFFFFFFULL;
200 }
201
202 static void get_locks(void)
203 {
204         unsigned int i;
205         struct flock fl;
206
207         if (lock_owner == getpid())
208                 return;
209
210         if (lock_owner != 0) {
211                 enum info_type type = RELEASE_LOCKS;
212                 assert(control_fd != -1);
213                 write_all(control_fd, &type, sizeof(type));
214         }
215
216         fl.l_whence = SEEK_SET;
217
218         for (i = 0; i < lock_num; i++) {
219                 fl.l_type = locks[i].type;
220                 fl.l_start = locks[i].start;
221                 if (locks[i].end == off_max())
222                         fl.l_len = 0;
223                 else
224                         fl.l_len = locks[i].end - locks[i].start + 1;
225
226                 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
227                         abort();
228         }
229         lock_owner = getpid();
230 }
231
232 struct saved_file {
233         struct saved_file *next;
234         int fd;
235         void *contents;
236         off_t off, len;
237 };
238
239 static struct saved_file *save_file(struct saved_file *next, int fd)
240 {
241         struct saved_file *s = malloc(sizeof(*s));
242
243         s->next = next;
244         s->fd = fd;
245         s->off = lseek(fd, 0, SEEK_CUR);
246         /* Special file?  Erk... */
247         assert(s->off != -1);
248         s->len = lseek(fd, 0, SEEK_END);
249         lseek(fd, 0, SEEK_SET);
250         s->contents = malloc(s->len);
251         if (read(fd, s->contents, s->len) != s->len)
252                 err(1, "Failed to save %zu bytes", (size_t)s->len);
253         lseek(fd, s->off, SEEK_SET);
254         return s;
255 }
256         
257 /* We have little choice but to save and restore open files: mmap means we
258  * can really intercept changes in the child.
259  *
260  * We could do non-mmap'ed files on demand, however. */
261 static struct saved_file *save_files(void)
262 {
263         struct saved_file *files = NULL;
264         int i;
265
266         /* Figure out the set of live fds. */
267         for (i = history_num - 2; i >= 0; i--) {
268                 if (history[i].type == FAILTEST_OPEN) {
269                         int fd = history[i].u.open.ret;
270                         /* Only do successful, writable fds. */
271                         if (fd < 0)
272                                 continue;
273
274                         /* If it was closed, cleanup == NULL. */
275                         if (!history[i].cleanup)
276                                 continue;
277
278                         if ((history[i].u.open.flags & O_RDWR) == O_RDWR) {
279                                 files = save_file(files, fd);
280                         } else if ((history[i].u.open.flags & O_WRONLY)
281                                    == O_WRONLY) {
282                                 /* FIXME: Handle O_WRONLY.  Open with O_RDWR? */
283                                 abort();
284                         }
285                 }
286         }
287
288         return files;
289 }
290
291 static void restore_files(struct saved_file *s)
292 {
293         while (s) {
294                 struct saved_file *next = s->next;
295
296                 lseek(s->fd, 0, SEEK_SET);
297                 if (write(s->fd, s->contents, s->len) != s->len)
298                         err(1, "Failed to restore %zu bytes", (size_t)s->len);
299                 if (ftruncate(s->fd, s->len) != 0)
300                         err(1, "Failed to trim file to length %zu",
301                             (size_t)s->len);
302                 free(s->contents);
303                 lseek(s->fd, s->off, SEEK_SET);
304                 free(s);
305                 s = next;
306         }
307 }
308
309 /* Free up memory, so valgrind doesn't report leaks. */
310 static void free_everything(void)
311 {
312         unsigned int i;
313
314         /* We don't do this in cleanup: needed even for failed opens. */
315         for (i = 0; i < history_num; i++) {
316                 if (history[i].type == FAILTEST_OPEN)
317                         free((char *)history[i].u.open.pathname);
318         }
319         free(history);
320 }
321
322 static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
323 {
324         int i;
325
326         /* For children, we don't care if they "failed" the testing. */
327         if (control_fd != -1)
328                 status = 0;
329
330         if (forced_cleanup)
331                 history_num--;
332
333         /* Cleanup everything, in reverse order. */
334         for (i = history_num - 1; i >= 0; i--) {
335                 if (!history[i].cleanup)
336                         continue;
337                 if (!forced_cleanup) {
338                         printf("Leak at %s:%u: --failpath=%s\n",
339                                history[i].file, history[i].line,
340                                failpath_string());
341                         status = 1;
342                 }
343                 history[i].cleanup(&history[i].u);
344         }
345
346         free_everything();
347         tell_parent(SUCCESS);
348         exit(status);
349 }
350
351 static bool should_fail(struct failtest_call *call)
352 {
353         int status;
354         int control[2], output[2];
355         enum info_type type = UNEXPECTED;
356         char *out = NULL;
357         size_t outlen = 0;
358         struct saved_file *files;
359
360         /* Are we probing? */
361         if (probe_count && --probe_count == 0)
362                 failtest_cleanup(true, 0);
363
364         if (call == &unrecorded_call)
365                 return false;
366
367         if (failpath) {
368                 /* + means continue after end, like normal. */
369                 if (*failpath == '+')
370                         failpath = NULL;
371                 else if (*failpath == '\0') {
372                         /* Continue, but don't inject errors. */
373                         return call->fail = false;
374                 } else {
375                         if (tolower((unsigned char)*failpath)
376                             != info_to_arg[call->type])
377                                 errx(1, "Failpath expected '%c' got '%c'\n",
378                                      info_to_arg[call->type], *failpath);
379                         call->fail = isupper((unsigned char)*(failpath++));
380                         return call->fail;
381                 }
382         }
383
384         /* Attach debugger if they asked for it. */
385         if (debugpath && history_num == strlen(debugpath)) {
386                 unsigned int i;
387
388                 for (i = 0; i < history_num; i++) {
389                         unsigned char c = info_to_arg[history[i].type];
390                         if (history[i].fail)
391                                 c = toupper(c);
392                         if (c != debugpath[i])
393                                 break;
394                 }
395                 if (i == history_num) {
396                         char str[80];
397
398                         /* Don't timeout. */
399                         signal(SIGUSR1, SIG_IGN);
400                         sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
401                                 getpid(), getpid());
402                         if (system(str) == 0)
403                                 sleep(5);
404                 }
405         }
406
407         if (failtest_hook) {
408                 switch (failtest_hook(history, history_num)) {
409                 case FAIL_OK:
410                         break;
411                 case FAIL_DONT_FAIL:
412                         call->fail = false;
413                         return false;
414                 case FAIL_PROBE:
415                         /* Already down probe path?  Stop now. */
416                         if (probe_count)
417                                 failtest_cleanup(true, 0);
418                         /* FIXME: We should run *parent* and run probe until
419                          * calls match up again. */
420                         probe_count = 3;
421                         break;
422                 default:
423                         abort();
424                 }
425         }
426
427         files = save_files();
428
429         /* We're going to fail in the child. */
430         call->fail = true;
431         if (pipe(control) != 0 || pipe(output) != 0)
432                 err(1, "opening pipe");
433
434         /* Prevent double-printing (in child and parent) */
435         fflush(stdout);
436         child = fork();
437         if (child == -1)
438                 err(1, "forking failed");
439
440         if (child == 0) {
441                 if (tracefd != -1) {
442                         struct timeval now;
443                         const char *p;
444                         gettimeofday(&now, NULL);
445                         if (now.tv_usec < start.tv_usec) {
446                                 now.tv_sec--;
447                                 now.tv_usec += 1000000;
448                         }
449                         now.tv_usec -= start.tv_usec;
450                         now.tv_sec -= start.tv_sec;
451                         p = failpath_string();
452                         trace("%u->%u (%u.%02u): %s (", getppid(), getpid(),
453                               (int)now.tv_sec, (int)now.tv_usec / 10000, p);
454                         free((char *)p);
455                         p = strrchr(history[history_num-1].file, '/');
456                         if (p)
457                                 trace("%s", p+1);
458                         else
459                                 trace("%s", history[history_num-1].file);
460                         trace(":%u)\n", history[history_num-1].line);
461                 }
462                 close(control[0]);
463                 close(output[0]);
464                 dup2(output[1], STDOUT_FILENO);
465                 dup2(output[1], STDERR_FILENO);
466                 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
467                         close(output[1]);
468                 control_fd = control[1];
469                 return true;
470         }
471
472         signal(SIGUSR1, hand_down);
473
474         close(control[1]);
475         close(output[1]);
476
477         /* We grab output so we can display it; we grab writes so we
478          * can compare. */
479         do {
480                 struct pollfd pfd[2];
481                 int ret;
482
483                 pfd[0].fd = output[0];
484                 pfd[0].events = POLLIN|POLLHUP;
485                 pfd[1].fd = control[0];
486                 pfd[1].events = POLLIN|POLLHUP;
487
488                 if (type == SUCCESS)
489                         ret = poll(pfd, 1, failtest_timeout_ms);
490                 else
491                         ret = poll(pfd, 2, failtest_timeout_ms);
492
493                 if (ret == 0)
494                         hand_down(SIGUSR1);
495                 if (ret < 0) {
496                         if (errno == EINTR)
497                                 continue;
498                         err(1, "Poll returned %i", ret);
499                 }
500
501                 if (pfd[0].revents & POLLIN) {
502                         ssize_t len;
503
504                         out = realloc(out, outlen + 8192);
505                         len = read(output[0], out + outlen, 8192);
506                         outlen += len;
507                 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
508                         if (read_all(control[0], &type, sizeof(type))) {
509                                 if (type == WRITE) {
510                                         if (!read_write_info(control[0]))
511                                                 break;
512                                 } else if (type == RELEASE_LOCKS) {
513                                         release_locks();
514                                         /* FIXME: Tell them we're done... */
515                                 }
516                         }
517                 } else if (pfd[0].revents & POLLHUP) {
518                         break;
519                 }
520         } while (type != FAILURE);
521
522         close(output[0]);
523         close(control[0]);
524         waitpid(child, &status, 0);
525         if (!WIFEXITED(status)) {
526                 if (WTERMSIG(status) == SIGUSR1)
527                         child_fail(out, outlen, "Timed out");
528                 else
529                         child_fail(out, outlen, "Killed by signal %u: ",
530                                    WTERMSIG(status));
531         }
532         /* Child printed failure already, just pass up exit code. */
533         if (type == FAILURE) {
534                 fprintf(stderr, "%.*s", (int)outlen, out);
535                 tell_parent(type);
536                 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
537         }
538         if (WEXITSTATUS(status) != 0)
539                 child_fail(out, outlen, "Exited with status %i: ",
540                            WEXITSTATUS(status));
541
542         free(out);
543         signal(SIGUSR1, SIG_DFL);
544
545         restore_files(files);
546
547         /* We continue onwards without failing. */
548         call->fail = false;
549         return false;
550 }
551
552 static void cleanup_calloc(struct calloc_call *call)
553 {
554         free(call->ret);
555 }
556
557 void *failtest_calloc(size_t nmemb, size_t size,
558                       const char *file, unsigned line)
559 {
560         struct failtest_call *p;
561         struct calloc_call call;
562         call.nmemb = nmemb;
563         call.size = size;
564         p = add_history(FAILTEST_CALLOC, file, line, &call);
565
566         if (should_fail(p)) {
567                 p->u.calloc.ret = NULL;
568                 p->error = ENOMEM;
569         } else {
570                 p->u.calloc.ret = calloc(nmemb, size);
571                 set_cleanup(p, cleanup_calloc, struct calloc_call);
572         }
573         errno = p->error;
574         return p->u.calloc.ret;
575 }
576
577 static void cleanup_malloc(struct malloc_call *call)
578 {
579         free(call->ret);
580 }
581
582 void *failtest_malloc(size_t size, const char *file, unsigned line)
583 {
584         struct failtest_call *p;
585         struct malloc_call call;
586         call.size = size;
587
588         p = add_history(FAILTEST_MALLOC, file, line, &call);
589         if (should_fail(p)) {
590                 p->u.calloc.ret = NULL;
591                 p->error = ENOMEM;
592         } else {
593                 p->u.calloc.ret = malloc(size);
594                 set_cleanup(p, cleanup_malloc, struct malloc_call);
595         }
596         errno = p->error;
597         return p->u.calloc.ret;
598 }
599
600 static void cleanup_realloc(struct realloc_call *call)
601 {
602         free(call->ret);
603 }
604
605 /* Walk back and find out if we got this ptr from a previous routine. */
606 static void fixup_ptr_history(void *ptr, unsigned int last)
607 {
608         int i;
609
610         /* Start at end of history, work back. */
611         for (i = last - 1; i >= 0; i--) {
612                 switch (history[i].type) {
613                 case FAILTEST_REALLOC:
614                         if (history[i].u.realloc.ret == ptr) {
615                                 history[i].cleanup = NULL;
616                                 return;
617                         }
618                         break;
619                 case FAILTEST_MALLOC:
620                         if (history[i].u.malloc.ret == ptr) {
621                                 history[i].cleanup = NULL;
622                                 return;
623                         }
624                         break;
625                 case FAILTEST_CALLOC:
626                         if (history[i].u.calloc.ret == ptr) {
627                                 history[i].cleanup = NULL;
628                                 return;
629                         }
630                         break;
631                 default:
632                         break;
633                 }
634         }
635 }
636
637 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
638 {
639         struct failtest_call *p;
640         struct realloc_call call;
641         call.size = size;
642         p = add_history(FAILTEST_REALLOC, file, line, &call);
643
644         /* FIXME: Try one child moving allocation, one not. */
645         if (should_fail(p)) {
646                 p->u.realloc.ret = NULL;
647                 p->error = ENOMEM;
648         } else {
649                 fixup_ptr_history(ptr, history_num-1);
650                 p->u.realloc.ret = realloc(ptr, size);
651                 set_cleanup(p, cleanup_realloc, struct realloc_call);
652         }
653         errno = p->error;
654         return p->u.realloc.ret;
655 }
656
657 void failtest_free(void *ptr)
658 {
659         fixup_ptr_history(ptr, history_num);
660         free(ptr);
661 }
662
663 static void cleanup_open(struct open_call *call)
664 {
665         close(call->ret);
666 }
667
668 int failtest_open(const char *pathname,
669                   const char *file, unsigned line, ...)
670 {
671         struct failtest_call *p;
672         struct open_call call;
673         va_list ap;
674
675         call.pathname = strdup(pathname);
676         va_start(ap, line);
677         call.flags = va_arg(ap, int);
678         if (call.flags & O_CREAT) {
679                 call.mode = va_arg(ap, mode_t);
680                 va_end(ap);
681         }
682         p = add_history(FAILTEST_OPEN, file, line, &call);
683         /* Avoid memory leak! */
684         if (p == &unrecorded_call)
685                 free((char *)call.pathname);
686         p->u.open.ret = open(pathname, call.flags, call.mode);
687
688         if (!failpath && p->u.open.ret == -1) {
689                 p->fail = false;
690                 p->error = errno;
691         } else if (should_fail(p)) {
692                 close(p->u.open.ret);
693                 p->u.open.ret = -1;
694                 /* FIXME: Play with error codes? */
695                 p->error = EACCES;
696         } else {
697                 set_cleanup(p, cleanup_open, struct open_call);
698         }
699         errno = p->error;
700         return p->u.open.ret;
701 }
702
703 static void cleanup_pipe(struct pipe_call *call)
704 {
705         if (!call->closed[0])
706                 close(call->fds[0]);
707         if (!call->closed[1])
708                 close(call->fds[1]);
709 }
710
711 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
712 {
713         struct failtest_call *p;
714         struct pipe_call call;
715
716         p = add_history(FAILTEST_PIPE, file, line, &call);
717         if (should_fail(p)) {
718                 p->u.open.ret = -1;
719                 /* FIXME: Play with error codes? */
720                 p->error = EMFILE;
721         } else {
722                 p->u.pipe.ret = pipe(p->u.pipe.fds);
723                 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
724                 set_cleanup(p, cleanup_pipe, struct pipe_call);
725         }
726         /* This causes valgrind to notice if they use pipefd[] after failure */
727         memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
728         errno = p->error;
729         return p->u.pipe.ret;
730 }
731
732 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
733                        const char *file, unsigned line)
734 {
735         struct failtest_call *p;
736         struct read_call call;
737         call.fd = fd;
738         call.buf = buf;
739         call.count = count;
740         call.off = off;
741         p = add_history(FAILTEST_READ, file, line, &call);
742
743         /* FIXME: Try partial read returns. */
744         if (should_fail(p)) {
745                 p->u.read.ret = -1;
746                 p->error = EIO;
747         } else {
748                 p->u.read.ret = pread(fd, buf, count, off);
749         }
750         errno = p->error;
751         return p->u.read.ret;
752 }
753
754 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
755                         const char *file, unsigned line)
756 {
757         struct failtest_call *p;
758         struct write_call call;
759
760         call.fd = fd;
761         call.buf = buf;
762         call.count = count;
763         call.off = off;
764         p = add_history(FAILTEST_WRITE, file, line, &call);
765
766         /* If we're a child, we need to make sure we write the same thing
767          * to non-files as the parent does, so tell it. */
768         if (control_fd != -1 && off == (off_t)-1) {
769                 enum info_type type = WRITE;
770
771                 write_all(control_fd, &type, sizeof(type));
772                 write_all(control_fd, &p->u.write, sizeof(p->u.write));
773                 write_all(control_fd, buf, count);
774         }
775
776         /* FIXME: Try partial write returns. */
777         if (should_fail(p)) {
778                 p->u.write.ret = -1;
779                 p->error = EIO;
780         } else {
781                 /* FIXME: We assume same write order in parent and child */
782                 if (off == (off_t)-1 && child_writes_num != 0) {
783                         if (child_writes[0].fd != fd)
784                                 errx(1, "Child wrote to fd %u, not %u?",
785                                      child_writes[0].fd, fd);
786                         if (child_writes[0].off != p->u.write.off)
787                                 errx(1, "Child wrote to offset %zu, not %zu?",
788                                      (size_t)child_writes[0].off,
789                                      (size_t)p->u.write.off);
790                         if (child_writes[0].count != count)
791                                 errx(1, "Child wrote length %zu, not %zu?",
792                                      child_writes[0].count, count);
793                         if (memcmp(child_writes[0].buf, buf, count)) {
794                                 child_fail(NULL, 0,
795                                            "Child wrote differently to"
796                                            " fd %u than we did!\n", fd);
797                         }
798                         free((char *)child_writes[0].buf);
799                         child_writes_num--;
800                         memmove(&child_writes[0], &child_writes[1],
801                                 sizeof(child_writes[0]) * child_writes_num);
802
803                         /* Is this is a socket or pipe, child wrote it
804                            already. */
805                         if (p->u.write.off == (off_t)-1) {
806                                 p->u.write.ret = count;
807                                 errno = p->error;
808                                 return p->u.write.ret;
809                         }
810                 }
811                 p->u.write.ret = pwrite(fd, buf, count, off);
812         }
813         errno = p->error;
814         return p->u.write.ret;
815 }
816
817 ssize_t failtest_read(int fd, void *buf, size_t count,
818                       const char *file, unsigned line)
819 {
820         return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
821                               file, line);
822 }
823
824 ssize_t failtest_write(int fd, const void *buf, size_t count,
825                        const char *file, unsigned line)
826 {
827         return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
828                                file, line);
829 }
830
831 static struct lock_info *WARN_UNUSED_RESULT
832 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
833 {
834         unsigned int i;
835         struct lock_info *l;
836
837         for (i = 0; i < lock_num; i++) {
838                 l = &locks[i];
839
840                 if (l->fd != fd)
841                         continue;
842                 /* Four cases we care about:
843                  * Start overlap:
844                  *      l =    |      |
845                  *      new = |   |
846                  * Mid overlap:
847                  *      l =    |      |
848                  *      new =    |  |
849                  * End overlap:
850                  *      l =    |      |
851                  *      new =      |    |
852                  * Total overlap:
853                  *      l =    |      |
854                  *      new = |         |
855                  */
856                 if (start > l->start && end < l->end) {
857                         /* Mid overlap: trim entry, add new one. */
858                         off_t new_start, new_end;
859                         new_start = end + 1;
860                         new_end = l->end;
861                         l->end = start - 1;
862                         locks = add_lock(locks,
863                                          fd, new_start, new_end, l->type);
864                         l = &locks[i];
865                 } else if (start <= l->start && end >= l->end) {
866                         /* Total overlap: eliminate entry. */
867                         l->end = 0;
868                         l->start = 1;
869                 } else if (end >= l->start && end < l->end) {
870                         /* Start overlap: trim entry. */
871                         l->start = end + 1;
872                 } else if (start > l->start && start <= l->end) {
873                         /* End overlap: trim entry. */
874                         l->end = start-1;
875                 }
876                 /* Nothing left?  Remove it. */
877                 if (l->end < l->start) {
878                         memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
879                         i--;
880                 }
881         }
882
883         if (type != F_UNLCK) {
884                 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
885                 l = &locks[lock_num++];
886                 l->fd = fd;
887                 l->start = start;
888                 l->end = end;
889                 l->type = type;
890         }
891         return locks;
892 }
893
894 /* We trap this so we can record it: we don't fail it. */
895 int failtest_close(int fd, const char *file, unsigned line)
896 {
897         int i;
898         struct close_call call;
899         struct failtest_call *p;
900
901         call.fd = fd;
902         p = add_history(FAILTEST_CLOSE, file, line, &call);
903         p->fail = false;
904
905         /* Consume close from failpath. */
906         if (failpath)
907                 if (should_fail(p))
908                         abort();
909
910         if (fd < 0)
911                 return close(fd);
912
913         /* Trace history to find source of fd. */
914         for (i = history_num-1; i >= 0; i--) {
915                 switch (history[i].type) {
916                 case FAILTEST_PIPE:
917                         /* From a pipe? */
918                         if (history[i].u.pipe.fds[0] == fd) {
919                                 assert(!history[i].u.pipe.closed[0]);
920                                 history[i].u.pipe.closed[0] = true;
921                                 if (history[i].u.pipe.closed[1])
922                                         history[i].cleanup = NULL;
923                                 goto out;
924                         }
925                         if (history[i].u.pipe.fds[1] == fd) {
926                                 assert(!history[i].u.pipe.closed[1]);
927                                 history[i].u.pipe.closed[1] = true;
928                                 if (history[i].u.pipe.closed[0])
929                                         history[i].cleanup = NULL;
930                                 goto out;
931                         }
932                         break;
933                 case FAILTEST_OPEN:
934                         if (history[i].u.open.ret == fd) {
935                                 assert((void *)history[i].cleanup
936                                        == (void *)cleanup_open);
937                                 history[i].cleanup = NULL;
938                                 goto out;
939                         }
940                         break;
941                 default:
942                         break;
943                 }
944         }
945
946 out:
947         locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
948         return close(fd);
949 }
950
951 /* Zero length means "to end of file" */
952 static off_t end_of(off_t start, off_t len)
953 {
954         if (len == 0)
955                 return off_max();
956         return start + len - 1;
957 }
958
959 /* FIXME: This only handles locks, really. */
960 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
961 {
962         struct failtest_call *p;
963         struct fcntl_call call;
964         va_list ap;
965
966         call.fd = fd;
967         call.cmd = cmd;
968
969         /* Argument extraction. */
970         switch (cmd) {
971         case F_SETFL:
972         case F_SETFD:
973                 va_start(ap, cmd);
974                 call.arg.l = va_arg(ap, long);
975                 va_end(ap);
976                 return fcntl(fd, cmd, call.arg.l);
977         case F_GETFD:
978         case F_GETFL:
979                 return fcntl(fd, cmd);
980         case F_GETLK:
981                 get_locks();
982                 va_start(ap, cmd);
983                 call.arg.fl = *va_arg(ap, struct flock *);
984                 va_end(ap);
985                 return fcntl(fd, cmd, &call.arg.fl);
986         case F_SETLK:
987         case F_SETLKW:
988                 va_start(ap, cmd);
989                 call.arg.fl = *va_arg(ap, struct flock *);
990                 va_end(ap);
991                 break;
992         default:
993                 /* This means you need to implement it here. */
994                 err(1, "failtest: unknown fcntl %u", cmd);
995         }
996
997         p = add_history(FAILTEST_FCNTL, file, line, &call);
998
999         if (should_fail(p)) {
1000                 p->u.fcntl.ret = -1;
1001                 if (p->u.fcntl.cmd == F_SETLK)
1002                         p->error = EAGAIN;
1003                 else
1004                         p->error = EDEADLK;
1005         } else {
1006                 get_locks();
1007                 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
1008                                        &p->u.fcntl.arg.fl);
1009                 if (p->u.fcntl.ret == -1)
1010                         p->error = errno;
1011                 else {
1012                         /* We don't handle anything else yet. */
1013                         assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1014                         locks = add_lock(locks,
1015                                          p->u.fcntl.fd,
1016                                          p->u.fcntl.arg.fl.l_start,
1017                                          end_of(p->u.fcntl.arg.fl.l_start,
1018                                                 p->u.fcntl.arg.fl.l_len),
1019                                          p->u.fcntl.arg.fl.l_type);
1020                 }
1021         }
1022         errno = p->error;
1023         return p->u.fcntl.ret;
1024 }
1025
1026 void failtest_init(int argc, char *argv[])
1027 {
1028         unsigned int i;
1029
1030         for (i = 1; i < argc; i++) {
1031                 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1032                         failpath = argv[i] + strlen("--failpath=");
1033                 } else if (strcmp(argv[i], "--tracepath") == 0) {
1034                         tracefd = dup(STDERR_FILENO);
1035                         failtest_timeout_ms = -1;
1036                 } else if (!strncmp(argv[i], "--debugpath=",
1037                                     strlen("--debugpath="))) {
1038                         debugpath = argv[i] + strlen("--debugpath=");
1039                 }
1040         }
1041         gettimeofday(&start, NULL);
1042 }
1043
1044 void failtest_exit(int status)
1045 {
1046         if (failtest_exit_check) {
1047                 if (!failtest_exit_check(history, history_num))
1048                         child_fail(NULL, 0, "failtest_exit_check failed\n");
1049         }
1050
1051         failtest_cleanup(false, status);
1052 }