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