]> git.ozlabs.org Git - ccan/blob - ccan/failtest/failtest.c
ec41e92b46e4cc514bdecb54598686b0a5e9b716
[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 = failpath_string();
527
528                 if (streq(path, debugpath)) {
529                         char str[80];
530
531                         /* Don't timeout. */
532                         signal(SIGUSR1, SIG_IGN);
533                         sprintf(str, "xterm -e gdb /proc/%d/exe %d &",
534                                 getpid(), getpid());
535                         if (system(str) == 0)
536                                 sleep(5);
537                 } else if (!strstarts(path, debugpath)) {
538                         fprintf(stderr, "--debugpath not followed: %s\n", path);
539                         debugpath = NULL;
540                 }
541                 free(path);
542         }
543
544         /* Are we probing?  If so, we never fail twice. */
545         if (probing)
546                 return call->fail = false;
547
548         /* Don't more than once in the same place. */
549         dup = failtable_get(&failtable, call);
550         if (dup)
551                 return call->fail = false;
552
553         if (failtest_hook) {
554                 switch (failtest_hook(&history)) {
555                 case FAIL_OK:
556                         break;
557                 case FAIL_PROBE:
558                         probing = true;
559                         break;
560                 case FAIL_DONT_FAIL:
561                         call->fail = false;
562                         return false;
563                 default:
564                         abort();
565                 }
566         }
567
568         /* Add it to our table of calls. */
569         failtable_add(&failtable, call);
570
571         files = save_files();
572
573         /* We're going to fail in the child. */
574         call->fail = true;
575         if (pipe(control) != 0 || pipe(output) != 0)
576                 err(1, "opening pipe");
577
578         /* Prevent double-printing (in child and parent) */
579         fflush(stdout);
580         child = fork();
581         if (child == -1)
582                 err(1, "forking failed");
583
584         if (child == 0) {
585                 if (tracefd != -1) {
586                         struct timeval diff;
587                         const char *p;
588                         char *failpath;
589                         struct failtest_call *c;
590
591                         c = tlist_tail(&history, struct failtest_call, list);
592                         diff = time_sub(time_now(), start);
593                         failpath = failpath_string();
594                         trace("%u->%u (%u.%02u): %s (", getppid(), getpid(),
595                               (int)diff.tv_sec, (int)diff.tv_usec / 10000,
596                               failpath);
597                         free(failpath);
598                         p = strrchr(c->file, '/');
599                         if (p)
600                                 trace("%s", p+1);
601                         else
602                                 trace("%s", c->file);
603                         trace(":%u)\n", c->line);
604                 }
605                 close(control[0]);
606                 close(output[0]);
607                 dup2(output[1], STDOUT_FILENO);
608                 dup2(output[1], STDERR_FILENO);
609                 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
610                         close(output[1]);
611                 control_fd = move_fd_to_high(control[1]);
612                 /* Valgrind spots the leak if we don't free these. */
613                 free_files(files);
614                 return true;
615         }
616
617         signal(SIGUSR1, hand_down);
618
619         close(control[1]);
620         close(output[1]);
621
622         /* We grab output so we can display it; we grab writes so we
623          * can compare. */
624         do {
625                 struct pollfd pfd[2];
626                 int ret;
627
628                 pfd[0].fd = output[0];
629                 pfd[0].events = POLLIN|POLLHUP;
630                 pfd[1].fd = control[0];
631                 pfd[1].events = POLLIN|POLLHUP;
632
633                 if (type == SUCCESS)
634                         ret = poll(pfd, 1, failtest_timeout_ms);
635                 else
636                         ret = poll(pfd, 2, failtest_timeout_ms);
637
638                 if (ret == 0)
639                         hand_down(SIGUSR1);
640                 if (ret < 0) {
641                         if (errno == EINTR)
642                                 continue;
643                         err(1, "Poll returned %i", ret);
644                 }
645
646                 if (pfd[0].revents & POLLIN) {
647                         ssize_t len;
648
649                         out = realloc(out, outlen + 8192);
650                         len = read(output[0], out + outlen, 8192);
651                         outlen += len;
652                 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
653                         if (read_all(control[0], &type, sizeof(type))) {
654                                 if (type == WRITE) {
655                                         if (!read_write_info(control[0]))
656                                                 break;
657                                 } else if (type == RELEASE_LOCKS) {
658                                         release_locks();
659                                         /* FIXME: Tell them we're done... */
660                                 }
661                         }
662                 } else if (pfd[0].revents & POLLHUP) {
663                         break;
664                 }
665         } while (type != FAILURE);
666
667         close(output[0]);
668         close(control[0]);
669         waitpid(child, &status, 0);
670         if (!WIFEXITED(status)) {
671                 if (WTERMSIG(status) == SIGUSR1)
672                         child_fail(out, outlen, "Timed out");
673                 else
674                         child_fail(out, outlen, "Killed by signal %u: ",
675                                    WTERMSIG(status));
676         }
677         /* Child printed failure already, just pass up exit code. */
678         if (type == FAILURE) {
679                 fprintf(stderr, "%.*s", (int)outlen, out);
680                 tell_parent(type);
681                 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
682         }
683         if (WEXITSTATUS(status) != 0)
684                 child_fail(out, outlen, "Exited with status %i: ",
685                            WEXITSTATUS(status));
686
687         free(out);
688         signal(SIGUSR1, SIG_DFL);
689
690         restore_files(files);
691
692         /* Only child does probe. */
693         probing = false;
694
695         /* We continue onwards without failing. */
696         call->fail = false;
697         return false;
698 }
699
700 static void cleanup_calloc(struct calloc_call *call)
701 {
702         free(call->ret);
703 }
704
705 void *failtest_calloc(size_t nmemb, size_t size,
706                       const char *file, unsigned line)
707 {
708         struct failtest_call *p;
709         struct calloc_call call;
710         call.nmemb = nmemb;
711         call.size = size;
712         p = add_history(FAILTEST_CALLOC, file, line, &call);
713
714         if (should_fail(p)) {
715                 p->u.calloc.ret = NULL;
716                 p->error = ENOMEM;
717         } else {
718                 p->u.calloc.ret = calloc(nmemb, size);
719                 set_cleanup(p, cleanup_calloc, struct calloc_call);
720         }
721         errno = p->error;
722         return p->u.calloc.ret;
723 }
724
725 static void cleanup_malloc(struct malloc_call *call)
726 {
727         free(call->ret);
728 }
729
730 void *failtest_malloc(size_t size, const char *file, unsigned line)
731 {
732         struct failtest_call *p;
733         struct malloc_call call;
734         call.size = size;
735
736         p = add_history(FAILTEST_MALLOC, file, line, &call);
737         if (should_fail(p)) {
738                 p->u.malloc.ret = NULL;
739                 p->error = ENOMEM;
740         } else {
741                 p->u.malloc.ret = malloc(size);
742                 set_cleanup(p, cleanup_malloc, struct malloc_call);
743         }
744         errno = p->error;
745         return p->u.malloc.ret;
746 }
747
748 static void cleanup_realloc(struct realloc_call *call)
749 {
750         free(call->ret);
751 }
752
753 /* Walk back and find out if we got this ptr from a previous routine. */
754 static void fixup_ptr_history(void *ptr)
755 {
756         struct failtest_call *i;
757
758         /* Start at end of history, work back. */
759         tlist_for_each_rev(&history, i, list) {
760                 switch (i->type) {
761                 case FAILTEST_REALLOC:
762                         if (i->u.realloc.ret == ptr) {
763                                 i->cleanup = NULL;
764                                 return;
765                         }
766                         break;
767                 case FAILTEST_MALLOC:
768                         if (i->u.malloc.ret == ptr) {
769                                 i->cleanup = NULL;
770                                 return;
771                         }
772                         break;
773                 case FAILTEST_CALLOC:
774                         if (i->u.calloc.ret == ptr) {
775                                 i->cleanup = NULL;
776                                 return;
777                         }
778                         break;
779                 default:
780                         break;
781                 }
782         }
783 }
784
785 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
786 {
787         struct failtest_call *p;
788         struct realloc_call call;
789         call.size = size;
790         p = add_history(FAILTEST_REALLOC, file, line, &call);
791
792         /* FIXME: Try one child moving allocation, one not. */
793         if (should_fail(p)) {
794                 p->u.realloc.ret = NULL;
795                 p->error = ENOMEM;
796         } else {
797                 /* Don't catch this one in the history fixup... */
798                 p->u.realloc.ret = NULL;
799                 fixup_ptr_history(ptr);
800                 p->u.realloc.ret = realloc(ptr, size);
801                 set_cleanup(p, cleanup_realloc, struct realloc_call);
802         }
803         errno = p->error;
804         return p->u.realloc.ret;
805 }
806
807 void failtest_free(void *ptr)
808 {
809         fixup_ptr_history(ptr);
810         free(ptr);
811 }
812
813 static void cleanup_open(struct open_call *call)
814 {
815         close(call->ret);
816 }
817
818 int failtest_open(const char *pathname,
819                   const char *file, unsigned line, ...)
820 {
821         struct failtest_call *p;
822         struct open_call call;
823         va_list ap;
824
825         call.pathname = strdup(pathname);
826         va_start(ap, line);
827         call.flags = va_arg(ap, int);
828         if (call.flags & O_CREAT) {
829                 call.mode = va_arg(ap, int);
830                 va_end(ap);
831         }
832         p = add_history(FAILTEST_OPEN, file, line, &call);
833         /* Avoid memory leak! */
834         if (p == &unrecorded_call)
835                 free((char *)call.pathname);
836         p->u.open.ret = open(pathname, call.flags, call.mode);
837
838         if (p->u.open.ret == -1) {
839                 p->fail = false;
840                 p->error = errno;
841         } else if (should_fail(p)) {
842                 close(p->u.open.ret);
843                 p->u.open.ret = -1;
844                 /* FIXME: Play with error codes? */
845                 p->error = EACCES;
846         } else {
847                 set_cleanup(p, cleanup_open, struct open_call);
848         }
849         errno = p->error;
850         return p->u.open.ret;
851 }
852
853 static void cleanup_pipe(struct pipe_call *call)
854 {
855         if (!call->closed[0])
856                 close(call->fds[0]);
857         if (!call->closed[1])
858                 close(call->fds[1]);
859 }
860
861 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
862 {
863         struct failtest_call *p;
864         struct pipe_call call;
865
866         p = add_history(FAILTEST_PIPE, file, line, &call);
867         if (should_fail(p)) {
868                 p->u.open.ret = -1;
869                 /* FIXME: Play with error codes? */
870                 p->error = EMFILE;
871         } else {
872                 p->u.pipe.ret = pipe(p->u.pipe.fds);
873                 p->u.pipe.closed[0] = p->u.pipe.closed[1] = false;
874                 set_cleanup(p, cleanup_pipe, struct pipe_call);
875         }
876         /* This causes valgrind to notice if they use pipefd[] after failure */
877         memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
878         errno = p->error;
879         return p->u.pipe.ret;
880 }
881
882 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
883                        const char *file, unsigned line)
884 {
885         struct failtest_call *p;
886         struct read_call call;
887         call.fd = fd;
888         call.buf = buf;
889         call.count = count;
890         call.off = off;
891         p = add_history(FAILTEST_READ, file, line, &call);
892
893         /* FIXME: Try partial read returns. */
894         if (should_fail(p)) {
895                 p->u.read.ret = -1;
896                 p->error = EIO;
897         } else {
898                 p->u.read.ret = pread(fd, buf, count, off);
899         }
900         errno = p->error;
901         return p->u.read.ret;
902 }
903
904 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
905                         const char *file, unsigned line)
906 {
907         struct failtest_call *p;
908         struct write_call call;
909
910         call.fd = fd;
911         call.buf = buf;
912         call.count = count;
913         call.off = off;
914         p = add_history(FAILTEST_WRITE, file, line, &call);
915
916         /* If we're a child, we need to make sure we write the same thing
917          * to non-files as the parent does, so tell it. */
918         if (control_fd != -1 && off == (off_t)-1) {
919                 enum info_type type = WRITE;
920
921                 write_all(control_fd, &type, sizeof(type));
922                 write_all(control_fd, &p->u.write, sizeof(p->u.write));
923                 write_all(control_fd, buf, count);
924         }
925
926         /* FIXME: Try partial write returns. */
927         if (should_fail(p)) {
928                 p->u.write.ret = -1;
929                 p->error = EIO;
930         } else {
931                 /* FIXME: We assume same write order in parent and child */
932                 if (off == (off_t)-1 && child_writes_num != 0) {
933                         if (child_writes[0].fd != fd)
934                                 errx(1, "Child wrote to fd %u, not %u?",
935                                      child_writes[0].fd, fd);
936                         if (child_writes[0].off != p->u.write.off)
937                                 errx(1, "Child wrote to offset %zu, not %zu?",
938                                      (size_t)child_writes[0].off,
939                                      (size_t)p->u.write.off);
940                         if (child_writes[0].count != count)
941                                 errx(1, "Child wrote length %zu, not %zu?",
942                                      child_writes[0].count, count);
943                         if (memcmp(child_writes[0].buf, buf, count)) {
944                                 child_fail(NULL, 0,
945                                            "Child wrote differently to"
946                                            " fd %u than we did!\n", fd);
947                         }
948                         free((char *)child_writes[0].buf);
949                         child_writes_num--;
950                         memmove(&child_writes[0], &child_writes[1],
951                                 sizeof(child_writes[0]) * child_writes_num);
952
953                         /* Is this is a socket or pipe, child wrote it
954                            already. */
955                         if (p->u.write.off == (off_t)-1) {
956                                 p->u.write.ret = count;
957                                 errno = p->error;
958                                 return p->u.write.ret;
959                         }
960                 }
961                 p->u.write.ret = pwrite(fd, buf, count, off);
962         }
963         errno = p->error;
964         return p->u.write.ret;
965 }
966
967 ssize_t failtest_read(int fd, void *buf, size_t count,
968                       const char *file, unsigned line)
969 {
970         return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
971                               file, line);
972 }
973
974 ssize_t failtest_write(int fd, const void *buf, size_t count,
975                        const char *file, unsigned line)
976 {
977         return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
978                                file, line);
979 }
980
981 static struct lock_info *WARN_UNUSED_RESULT
982 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
983 {
984         unsigned int i;
985         struct lock_info *l;
986
987         for (i = 0; i < lock_num; i++) {
988                 l = &locks[i];
989
990                 if (l->fd != fd)
991                         continue;
992                 /* Four cases we care about:
993                  * Start overlap:
994                  *      l =    |      |
995                  *      new = |   |
996                  * Mid overlap:
997                  *      l =    |      |
998                  *      new =    |  |
999                  * End overlap:
1000                  *      l =    |      |
1001                  *      new =      |    |
1002                  * Total overlap:
1003                  *      l =    |      |
1004                  *      new = |         |
1005                  */
1006                 if (start > l->start && end < l->end) {
1007                         /* Mid overlap: trim entry, add new one. */
1008                         off_t new_start, new_end;
1009                         new_start = end + 1;
1010                         new_end = l->end;
1011                         l->end = start - 1;
1012                         locks = add_lock(locks,
1013                                          fd, new_start, new_end, l->type);
1014                         l = &locks[i];
1015                 } else if (start <= l->start && end >= l->end) {
1016                         /* Total overlap: eliminate entry. */
1017                         l->end = 0;
1018                         l->start = 1;
1019                 } else if (end >= l->start && end < l->end) {
1020                         /* Start overlap: trim entry. */
1021                         l->start = end + 1;
1022                 } else if (start > l->start && start <= l->end) {
1023                         /* End overlap: trim entry. */
1024                         l->end = start-1;
1025                 }
1026                 /* Nothing left?  Remove it. */
1027                 if (l->end < l->start) {
1028                         memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
1029                         i--;
1030                 }
1031         }
1032
1033         if (type != F_UNLCK) {
1034                 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
1035                 l = &locks[lock_num++];
1036                 l->fd = fd;
1037                 l->start = start;
1038                 l->end = end;
1039                 l->type = type;
1040         }
1041         return locks;
1042 }
1043
1044 /* We trap this so we can record it: we don't fail it. */
1045 int failtest_close(int fd, const char *file, unsigned line)
1046 {
1047         struct failtest_call *i;
1048         struct close_call call;
1049         struct failtest_call *p;
1050
1051         call.fd = fd;
1052         p = add_history(FAILTEST_CLOSE, file, line, &call);
1053         p->fail = false;
1054
1055         /* Consume close from failpath. */
1056         if (failpath)
1057                 if (should_fail(p))
1058                         abort();
1059
1060         if (fd < 0)
1061                 return close(fd);
1062
1063         /* Trace history to find source of fd. */
1064         tlist_for_each_rev(&history, i, list) {
1065                 switch (i->type) {
1066                 case FAILTEST_PIPE:
1067                         /* From a pipe? */
1068                         if (i->u.pipe.fds[0] == fd) {
1069                                 assert(!i->u.pipe.closed[0]);
1070                                 i->u.pipe.closed[0] = true;
1071                                 if (i->u.pipe.closed[1])
1072                                         i->cleanup = NULL;
1073                                 goto out;
1074                         }
1075                         if (i->u.pipe.fds[1] == fd) {
1076                                 assert(!i->u.pipe.closed[1]);
1077                                 i->u.pipe.closed[1] = true;
1078                                 if (i->u.pipe.closed[0])
1079                                         i->cleanup = NULL;
1080                                 goto out;
1081                         }
1082                         break;
1083                 case FAILTEST_OPEN:
1084                         if (i->u.open.ret == fd) {
1085                                 assert((void *)i->cleanup
1086                                        == (void *)cleanup_open);
1087                                 i->cleanup = NULL;
1088                                 goto out;
1089                         }
1090                         break;
1091                 default:
1092                         break;
1093                 }
1094         }
1095
1096 out:
1097         locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
1098         return close(fd);
1099 }
1100
1101 /* Zero length means "to end of file" */
1102 static off_t end_of(off_t start, off_t len)
1103 {
1104         if (len == 0)
1105                 return off_max();
1106         return start + len - 1;
1107 }
1108
1109 /* FIXME: This only handles locks, really. */
1110 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
1111 {
1112         struct failtest_call *p;
1113         struct fcntl_call call;
1114         va_list ap;
1115
1116         call.fd = fd;
1117         call.cmd = cmd;
1118
1119         /* Argument extraction. */
1120         switch (cmd) {
1121         case F_SETFL:
1122         case F_SETFD:
1123                 va_start(ap, cmd);
1124                 call.arg.l = va_arg(ap, long);
1125                 va_end(ap);
1126                 return fcntl(fd, cmd, call.arg.l);
1127         case F_GETFD:
1128         case F_GETFL:
1129                 return fcntl(fd, cmd);
1130         case F_GETLK:
1131                 get_locks();
1132                 va_start(ap, cmd);
1133                 call.arg.fl = *va_arg(ap, struct flock *);
1134                 va_end(ap);
1135                 return fcntl(fd, cmd, &call.arg.fl);
1136         case F_SETLK:
1137         case F_SETLKW:
1138                 va_start(ap, cmd);
1139                 call.arg.fl = *va_arg(ap, struct flock *);
1140                 va_end(ap);
1141                 break;
1142         default:
1143                 /* This means you need to implement it here. */
1144                 err(1, "failtest: unknown fcntl %u", cmd);
1145         }
1146
1147         p = add_history(FAILTEST_FCNTL, file, line, &call);
1148
1149         if (should_fail(p)) {
1150                 p->u.fcntl.ret = -1;
1151                 if (p->u.fcntl.cmd == F_SETLK)
1152                         p->error = EAGAIN;
1153                 else
1154                         p->error = EDEADLK;
1155         } else {
1156                 get_locks();
1157                 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
1158                                        &p->u.fcntl.arg.fl);
1159                 if (p->u.fcntl.ret == -1)
1160                         p->error = errno;
1161                 else {
1162                         /* We don't handle anything else yet. */
1163                         assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
1164                         locks = add_lock(locks,
1165                                          p->u.fcntl.fd,
1166                                          p->u.fcntl.arg.fl.l_start,
1167                                          end_of(p->u.fcntl.arg.fl.l_start,
1168                                                 p->u.fcntl.arg.fl.l_len),
1169                                          p->u.fcntl.arg.fl.l_type);
1170                 }
1171         }
1172         errno = p->error;
1173         return p->u.fcntl.ret;
1174 }
1175
1176 pid_t failtest_getpid(const char *file, unsigned line)
1177 {
1178         /* You must call failtest_init first! */
1179         assert(orig_pid);
1180         return orig_pid;
1181 }
1182         
1183 void failtest_init(int argc, char *argv[])
1184 {
1185         unsigned int i;
1186
1187         orig_pid = getpid();
1188
1189         warnfd = move_fd_to_high(dup(STDERR_FILENO));
1190         for (i = 1; i < argc; i++) {
1191                 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
1192                         failpath = argv[i] + strlen("--failpath=");
1193                 } else if (strcmp(argv[i], "--tracepath") == 0) {
1194                         tracefd = warnfd;
1195                         failtest_timeout_ms = -1;
1196                 } else if (!strncmp(argv[i], "--debugpath=",
1197                                     strlen("--debugpath="))) {
1198                         debugpath = argv[i] + strlen("--debugpath=");
1199                 }
1200         }
1201         failtable_init(&failtable);
1202         start = time_now();
1203 }
1204
1205 bool failtest_has_failed(void)
1206 {
1207         return control_fd != -1;
1208 }
1209
1210 void failtest_exit(int status)
1211 {
1212         if (failtest_exit_check) {
1213                 if (!failtest_exit_check(&history))
1214                         child_fail(NULL, 0, "failtest_exit_check failed\n");
1215         }
1216
1217         failtest_cleanup(false, status);
1218 }