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