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