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