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