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