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