]> git.ozlabs.org Git - ccan/blob - ccan/failtest/failtest.c
ad7e0feac1ec00be4b161c545e3e5c497a8cd8f6
[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[] = "mceoprwf";
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                 child_fail(out, outlen, "Killed by signal %u: ",
460                            WTERMSIG(status));
461         /* Child printed failure already, just pass up exit code. */
462         if (type == FAILURE) {
463                 fprintf(stderr, "%.*s", (int)outlen, out);
464                 tell_parent(type);
465                 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
466         }
467         if (WEXITSTATUS(status) != 0)
468                 child_fail(out, outlen, "Exited with status %i: ",
469                            WEXITSTATUS(status));
470
471         free(out);
472         signal(SIGUSR1, SIG_DFL);
473
474         restore_files(files);
475
476         /* We continue onwards without failing. */
477         call->fail = false;
478         return false;
479 }
480
481 static void cleanup_calloc(struct calloc_call *call)
482 {
483         free(call->ret);
484 }
485
486 void *failtest_calloc(size_t nmemb, size_t size,
487                       const char *file, unsigned line)
488 {
489         struct failtest_call *p;
490         struct calloc_call call;
491         call.nmemb = nmemb;
492         call.size = size;
493         p = add_history(FAILTEST_CALLOC, file, line, &call);
494
495         if (should_fail(p)) {
496                 p->u.calloc.ret = NULL;
497                 p->error = ENOMEM;
498         } else {
499                 p->u.calloc.ret = calloc(nmemb, size);
500                 set_cleanup(p, cleanup_calloc, struct calloc_call);
501         }
502         errno = p->error;
503         return p->u.calloc.ret;
504 }
505
506 static void cleanup_malloc(struct malloc_call *call)
507 {
508         free(call->ret);
509 }
510
511 void *failtest_malloc(size_t size, const char *file, unsigned line)
512 {
513         struct failtest_call *p;
514         struct malloc_call call;
515         call.size = size;
516
517         p = add_history(FAILTEST_MALLOC, file, line, &call);
518         if (should_fail(p)) {
519                 p->u.calloc.ret = NULL;
520                 p->error = ENOMEM;
521         } else {
522                 p->u.calloc.ret = malloc(size);
523                 set_cleanup(p, cleanup_malloc, struct malloc_call);
524         }
525         errno = p->error;
526         return p->u.calloc.ret;
527 }
528
529 static void cleanup_realloc(struct realloc_call *call)
530 {
531         free(call->ret);
532 }
533
534 /* Walk back and find out if we got this ptr from a previous routine. */
535 static void fixup_ptr_history(void *ptr, unsigned int last)
536 {
537         int i;
538
539         /* Start at end of history, work back. */
540         for (i = last - 1; i >= 0; i--) {
541                 switch (history[i].type) {
542                 case FAILTEST_REALLOC:
543                         if (history[i].u.realloc.ret == ptr) {
544                                 history[i].cleanup = NULL;
545                                 return;
546                         }
547                         break;
548                 case FAILTEST_MALLOC:
549                         if (history[i].u.malloc.ret == ptr) {
550                                 history[i].cleanup = NULL;
551                                 return;
552                         }
553                         break;
554                 case FAILTEST_CALLOC:
555                         if (history[i].u.calloc.ret == ptr) {
556                                 history[i].cleanup = NULL;
557                                 return;
558                         }
559                         break;
560                 default:
561                         break;
562                 }
563         }
564 }
565
566 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
567 {
568         struct failtest_call *p;
569         struct realloc_call call;
570         call.size = size;
571         p = add_history(FAILTEST_REALLOC, file, line, &call);
572
573         /* FIXME: Try one child moving allocation, one not. */
574         if (should_fail(p)) {
575                 p->u.realloc.ret = NULL;
576                 p->error = ENOMEM;
577         } else {
578                 fixup_ptr_history(ptr, history_num-1);
579                 p->u.realloc.ret = realloc(ptr, size);
580                 set_cleanup(p, cleanup_realloc, struct realloc_call);
581         }
582         errno = p->error;
583         return p->u.realloc.ret;
584 }
585
586 void failtest_free(void *ptr)
587 {
588         fixup_ptr_history(ptr, history_num);
589         free(ptr);
590 }
591
592 static void cleanup_open(struct open_call *call)
593 {
594         close(call->ret);
595 }
596
597 int failtest_open(const char *pathname,
598                   const char *file, unsigned line, ...)
599 {
600         struct failtest_call *p;
601         struct open_call call;
602         va_list ap;
603
604         call.pathname = strdup(pathname);
605         va_start(ap, line);
606         call.flags = va_arg(ap, int);
607         if (call.flags & O_CREAT) {
608                 call.mode = va_arg(ap, mode_t);
609                 va_end(ap);
610         }
611         p = add_history(FAILTEST_OPEN, file, line, &call);
612         /* Avoid memory leak! */
613         if (p == &unrecorded_call)
614                 free((char *)call.pathname);
615         p->u.open.ret = open(pathname, call.flags, call.mode);
616
617         if (!failpath && p->u.open.ret == -1) {
618                 p->fail = false;
619                 p->error = errno;
620         } else if (should_fail(p)) {
621                 close(p->u.open.ret);
622                 p->u.open.ret = -1;
623                 /* FIXME: Play with error codes? */
624                 p->error = EACCES;
625         } else {
626                 set_cleanup(p, cleanup_open, struct open_call);
627         }
628         errno = p->error;
629         return p->u.open.ret;
630 }
631
632 static void cleanup_pipe(struct pipe_call *call)
633 {
634         if (!call->closed[0])
635                 close(call->fds[0]);
636         if (!call->closed[1])
637                 close(call->fds[1]);
638 }
639
640 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
641 {
642         struct failtest_call *p;
643         struct pipe_call call;
644
645         p = add_history(FAILTEST_PIPE, file, line, &call);
646         if (should_fail(p)) {
647                 p->u.open.ret = -1;
648                 /* FIXME: Play with error codes? */
649                 p->error = EMFILE;
650         } else {
651                 p->u.pipe.ret = pipe(p->u.pipe.fds);
652                 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
653                 set_cleanup(p, cleanup_pipe, struct pipe_call);
654         }
655         /* This causes valgrind to notice if they use pipefd[] after failure */
656         memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
657         errno = p->error;
658         return p->u.pipe.ret;
659 }
660
661 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
662                        const char *file, unsigned line)
663 {
664         struct failtest_call *p;
665         struct read_call call;
666         call.fd = fd;
667         call.buf = buf;
668         call.count = count;
669         call.off = off;
670         p = add_history(FAILTEST_READ, file, line, &call);
671
672         /* FIXME: Try partial read returns. */
673         if (should_fail(p)) {
674                 p->u.read.ret = -1;
675                 p->error = EIO;
676         } else {
677                 p->u.read.ret = pread(fd, buf, count, off);
678         }
679         errno = p->error;
680         return p->u.read.ret;
681 }
682
683 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
684                         const char *file, unsigned line)
685 {
686         struct failtest_call *p;
687         struct write_call call;
688
689         call.fd = fd;
690         call.buf = buf;
691         call.count = count;
692         call.off = off;
693         p = add_history(FAILTEST_WRITE, file, line, &call);
694
695         /* If we're a child, we need to make sure we write the same thing
696          * to non-files as the parent does, so tell it. */
697         if (control_fd != -1 && off == (off_t)-1) {
698                 enum info_type type = WRITE;
699
700                 write_all(control_fd, &type, sizeof(type));
701                 write_all(control_fd, &p->u.write, sizeof(p->u.write));
702                 write_all(control_fd, buf, count);
703         }
704
705         /* FIXME: Try partial write returns. */
706         if (should_fail(p)) {
707                 p->u.write.ret = -1;
708                 p->error = EIO;
709         } else {
710                 /* FIXME: We assume same write order in parent and child */
711                 if (off == (off_t)-1 && child_writes_num != 0) {
712                         if (child_writes[0].fd != fd)
713                                 errx(1, "Child wrote to fd %u, not %u?",
714                                      child_writes[0].fd, fd);
715                         if (child_writes[0].off != p->u.write.off)
716                                 errx(1, "Child wrote to offset %zu, not %zu?",
717                                      (size_t)child_writes[0].off,
718                                      (size_t)p->u.write.off);
719                         if (child_writes[0].count != count)
720                                 errx(1, "Child wrote length %zu, not %zu?",
721                                      child_writes[0].count, count);
722                         if (memcmp(child_writes[0].buf, buf, count)) {
723                                 child_fail(NULL, 0,
724                                            "Child wrote differently to"
725                                            " fd %u than we did!\n", fd);
726                         }
727                         free((char *)child_writes[0].buf);
728                         child_writes_num--;
729                         memmove(&child_writes[0], &child_writes[1],
730                                 sizeof(child_writes[0]) * child_writes_num);
731
732                         /* Is this is a socket or pipe, child wrote it
733                            already. */
734                         if (p->u.write.off == (off_t)-1) {
735                                 p->u.write.ret = count;
736                                 errno = p->error;
737                                 return p->u.write.ret;
738                         }
739                 }
740                 p->u.write.ret = pwrite(fd, buf, count, off);
741         }
742         errno = p->error;
743         return p->u.write.ret;
744 }
745
746 ssize_t failtest_read(int fd, void *buf, size_t count,
747                       const char *file, unsigned line)
748 {
749         return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
750                               file, line);
751 }
752
753 ssize_t failtest_write(int fd, const void *buf, size_t count,
754                        const char *file, unsigned line)
755 {
756         return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
757                                file, line);
758 }
759
760 static struct lock_info *WARN_UNUSED_RESULT
761 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
762 {
763         unsigned int i;
764         struct lock_info *l;
765
766         for (i = 0; i < lock_num; i++) {
767                 l = &locks[i];
768
769                 if (l->fd != fd)
770                         continue;
771                 /* Four cases we care about:
772                  * Start overlap:
773                  *      l =    |      |
774                  *      new = |   |
775                  * Mid overlap:
776                  *      l =    |      |
777                  *      new =    |  |
778                  * End overlap:
779                  *      l =    |      |
780                  *      new =      |    |
781                  * Total overlap:
782                  *      l =    |      |
783                  *      new = |         |
784                  */
785                 if (start > l->start && end < l->end) {
786                         /* Mid overlap: trim entry, add new one. */
787                         off_t new_start, new_end;
788                         new_start = end + 1;
789                         new_end = l->end;
790                         l->end = start - 1;
791                         locks = add_lock(locks,
792                                          fd, new_start, new_end, l->type);
793                         l = &locks[i];
794                 } else if (start <= l->start && end >= l->end) {
795                         /* Total overlap: eliminate entry. */
796                         l->end = 0;
797                         l->start = 1;
798                 } else if (end >= l->start && end < l->end) {
799                         /* Start overlap: trim entry. */
800                         l->start = end + 1;
801                 } else if (start > l->start && start <= l->end) {
802                         /* End overlap: trim entry. */
803                         l->end = start-1;
804                 }
805                 /* Nothing left?  Remove it. */
806                 if (l->end < l->start) {
807                         memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
808                         i--;
809                 }
810         }
811
812         if (type != F_UNLCK) {
813                 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
814                 l = &locks[lock_num++];
815                 l->fd = fd;
816                 l->start = start;
817                 l->end = end;
818                 l->type = type;
819         }
820         return locks;
821 }
822
823 /* We trap this so we can record it: we don't fail it. */
824 int failtest_close(int fd)
825 {
826         int i;
827
828         if (fd < 0)
829                 return close(fd);
830
831         /* Trace history to find source of fd. */
832         for (i = history_num-1; i >= 0; i--) {
833                 switch (history[i].type) {
834                 case FAILTEST_PIPE:
835                         /* From a pipe? */
836                         if (history[i].u.pipe.fds[0] == fd) {
837                                 assert(!history[i].u.pipe.closed[0]);
838                                 history[i].u.pipe.closed[0] = true;
839                                 if (history[i].u.pipe.closed[1])
840                                         history[i].cleanup = NULL;
841                                 goto out;
842                         }
843                         if (history[i].u.pipe.fds[1] == fd) {
844                                 assert(!history[i].u.pipe.closed[1]);
845                                 history[i].u.pipe.closed[1] = true;
846                                 if (history[i].u.pipe.closed[0])
847                                         history[i].cleanup = NULL;
848                                 goto out;
849                         }
850                         break;
851                 case FAILTEST_OPEN:
852                         if (history[i].u.open.ret == fd) {
853                                 assert((void *)history[i].cleanup
854                                        == (void *)cleanup_open);
855                                 history[i].cleanup = NULL;
856                                 goto out;
857                         }
858                         break;
859                 default:
860                         break;
861                 }
862         }
863
864 out:
865         locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
866         return close(fd);
867 }
868
869 /* Zero length means "to end of file" */
870 static off_t end_of(off_t start, off_t len)
871 {
872         if (len == 0)
873                 return off_max();
874         return start + len - 1;
875 }
876
877 /* FIXME: This only handles locks, really. */
878 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
879 {
880         struct failtest_call *p;
881         struct fcntl_call call;
882         va_list ap;
883
884         call.fd = fd;
885         call.cmd = cmd;
886
887         /* Argument extraction. */
888         switch (cmd) {
889         case F_SETFL:
890         case F_SETFD:
891                 va_start(ap, cmd);
892                 call.arg.l = va_arg(ap, long);
893                 va_end(ap);
894                 return fcntl(fd, cmd, call.arg.l);
895         case F_GETFD:
896         case F_GETFL:
897                 return fcntl(fd, cmd);
898         case F_GETLK:
899                 get_locks();
900                 va_start(ap, cmd);
901                 call.arg.fl = *va_arg(ap, struct flock *);
902                 va_end(ap);
903                 return fcntl(fd, cmd, &call.arg.fl);
904         case F_SETLK:
905         case F_SETLKW:
906                 va_start(ap, cmd);
907                 call.arg.fl = *va_arg(ap, struct flock *);
908                 va_end(ap);
909                 break;
910         default:
911                 /* This means you need to implement it here. */
912                 err(1, "failtest: unknown fcntl %u", cmd);
913         }
914
915         p = add_history(FAILTEST_FCNTL, file, line, &call);
916         get_locks();
917
918         if (should_fail(p)) {
919                 p->u.fcntl.ret = -1;
920                 if (p->u.fcntl.cmd == F_SETLK)
921                         p->error = EAGAIN;
922                 else
923                         p->error = EDEADLK;
924         } else {
925                 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
926                                        &p->u.fcntl.arg.fl);
927                 if (p->u.fcntl.ret == -1)
928                         p->error = errno;
929                 else {
930                         /* We don't handle anything else yet. */
931                         assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
932                         locks = add_lock(locks,
933                                          p->u.fcntl.fd,
934                                          p->u.fcntl.arg.fl.l_start,
935                                          end_of(p->u.fcntl.arg.fl.l_start,
936                                                 p->u.fcntl.arg.fl.l_len),
937                                          p->u.fcntl.arg.fl.l_type);
938                 }
939         }
940         errno = p->error;
941         return p->u.fcntl.ret;
942 }
943
944 void failtest_init(int argc, char *argv[])
945 {
946         unsigned int i;
947
948         for (i = 1; i < argc; i++) {
949                 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
950                         failpath = argv[i] + strlen("--failpath=");
951                 } else if (strcmp(argv[i], "--tracepath") == 0) {
952                         tracefd = dup(STDERR_FILENO);
953                         failtest_timeout_ms = -1;
954                 } else if (!strncmp(argv[i], "--debugpath=",
955                                     strlen("--debugpath="))) {
956                         debugpath = argv[i] + strlen("--debugpath=");
957                 }
958         }
959         gettimeofday(&start, NULL);
960 }
961
962 /* Free up memory, so valgrind doesn't report leaks. */
963 static void free_everything(void)
964 {
965         unsigned int i;
966
967         /* We don't do this in cleanup: needed even for failed opens. */
968         for (i = 0; i < history_num; i++) {
969                 if (history[i].type == FAILTEST_OPEN)
970                         free((char *)history[i].u.open.pathname);
971         }
972         free(history);
973 }
974
975 void failtest_exit(int status)
976 {
977         int i;
978
979         if (control_fd == -1) {
980                 free_everything();
981                 exit(status);
982         }
983
984         if (failtest_exit_check) {
985                 if (!failtest_exit_check(history, history_num))
986                         child_fail(NULL, 0, "failtest_exit_check failed\n");
987         }
988
989         /* Cleanup everything, in reverse order. */
990         for (i = history_num - 1; i >= 0; i--)
991                 if (history[i].cleanup)
992                         history[i].cleanup(&history[i].u);
993
994         free_everything();
995         tell_parent(SUCCESS);
996         exit(0);
997 }