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