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