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