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