]> git.ozlabs.org Git - ccan/blob - ccan/failtest/failtest.c
failtest: --tracepath
[ccan] / ccan / failtest / failtest.c
1 #include <stdarg.h>
2 #include <string.h>
3 #include <stdio.h>
4 #include <stdarg.h>
5 #include <ctype.h>
6 #include <err.h>
7 #include <unistd.h>
8 #include <poll.h>
9 #include <errno.h>
10 #include <sys/types.h>
11 #include <sys/wait.h>
12 #include <sys/stat.h>
13 #include <sys/time.h>
14 #include <assert.h>
15 #include <ccan/read_write_all/read_write_all.h>
16 #include <ccan/failtest/failtest_proto.h>
17 #include <ccan/failtest/failtest.h>
18 #include <ccan/build_assert/build_assert.h>
19
20 bool (*failtest_hook)(struct failtest_call *history, unsigned num)
21 = failtest_default_hook;
22
23 static int tracefd = -1;
24
25 unsigned int failtest_timeout_ms = 20000;
26
27 const char *failpath;
28
29 enum info_type {
30         WRITE,
31         RELEASE_LOCKS,
32         FAILURE,
33         SUCCESS,
34         UNEXPECTED
35 };
36
37 struct write_info_hdr {
38         size_t len;
39         off_t offset;
40         int fd;
41 };
42
43 struct fd_orig {
44         int fd;
45         off_t offset;
46         size_t size;
47         bool dupped;
48 };
49
50 struct write_info {
51         struct write_info_hdr hdr;
52         char *data;
53         size_t oldlen;
54         char *olddata;
55 };
56
57 struct lock_info {
58         int fd;
59         /* end is inclusive: you can't have a 0-byte lock. */
60         off_t start, end;
61         int type;
62 };
63
64 bool (*failtest_exit_check)(struct failtest_call *history, unsigned num);
65
66 static struct failtest_call *history = NULL;
67 static unsigned int history_num = 0;
68 static int control_fd = -1;
69 static struct timeval start;
70
71 static struct write_info *writes = NULL;
72 static unsigned int writes_num = 0;
73
74 static struct write_info *child_writes = NULL;
75 static unsigned int child_writes_num = 0;
76
77 static struct fd_orig *fd_orig = NULL;
78 static unsigned int fd_orig_num = 0;
79
80 static pid_t lock_owner;
81 static struct lock_info *locks = NULL;
82 static unsigned int lock_num = 0;
83
84 static const char info_to_arg[] = "mceoprwf";
85
86 /* Dummy call used for failtest_undo wrappers. */
87 static struct failtest_call unrecorded_call;
88
89 static struct failtest_call *add_history_(enum failtest_call_type type,
90                                           const char *file,
91                                           unsigned int line,
92                                           const void *elem,
93                                           size_t elem_size)
94 {
95         /* NULL file is how we suppress failure. */
96         if (!file)
97                 return &unrecorded_call;
98
99         history = realloc(history, (history_num + 1) * sizeof(*history));
100         history[history_num].type = type;
101         history[history_num].file = file;
102         history[history_num].line = line;
103         memcpy(&history[history_num].u, elem, elem_size);
104         return &history[history_num++];
105 }
106
107 #define add_history(type, file, line, elem) \
108         add_history_((type), (file), (line), (elem), sizeof(*(elem)))
109
110 static void save_fd_orig(int fd)
111 {
112         unsigned int i;
113
114         for (i = 0; i < fd_orig_num; i++)
115                 if (fd_orig[i].fd == fd)
116                         return;
117
118         fd_orig = realloc(fd_orig, (fd_orig_num + 1) * sizeof(*fd_orig));
119         fd_orig[fd_orig_num].fd = fd;
120         fd_orig[fd_orig_num].dupped = false;
121         fd_orig[fd_orig_num].offset = lseek(fd, 0, SEEK_CUR);
122         fd_orig[fd_orig_num].size = lseek(fd, 0, SEEK_END);
123         lseek(fd, fd_orig[fd_orig_num].offset, SEEK_SET);
124         fd_orig_num++;
125 }
126
127 bool failtest_default_hook(struct failtest_call *history, unsigned num)
128 {
129         return true;
130 }
131
132 static bool read_write_info(int fd)
133 {
134         struct write_info_hdr hdr;
135
136         if (!read_all(fd, &hdr, sizeof(hdr)))
137                 return false;
138
139         child_writes = realloc(child_writes,
140                                (child_writes_num+1) * sizeof(child_writes[0]));
141         child_writes[child_writes_num].hdr = hdr;
142         child_writes[child_writes_num].data = malloc(hdr.len);
143         if (!read_all(fd, child_writes[child_writes_num].data, hdr.len))
144                 return false;
145
146         child_writes_num++;
147         return true;
148 }
149
150 static char *failpath_string(void)
151 {
152         unsigned int i;
153         char *ret = malloc(history_num + 1);
154
155         for (i = 0; i < history_num; i++) {
156                 ret[i] = info_to_arg[history[i].type];
157                 if (history[i].fail)
158                         ret[i] = toupper(ret[i]);
159         }
160         ret[i] = '\0';
161         return ret;
162 }
163
164 static void tell_parent(enum info_type type)
165 {
166         if (control_fd != -1)
167                 write_all(control_fd, &type, sizeof(type));
168 }
169
170 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
171 {
172         va_list ap;
173         char *path = failpath_string();
174
175         va_start(ap, fmt);
176         vfprintf(stderr, fmt, ap);
177         va_end(ap);
178
179         fprintf(stderr, "%.*s", (int)outlen, out);
180         printf("To reproduce: --failpath=%s\n", path);
181         free(path);
182         tell_parent(FAILURE);
183         exit(1);
184 }
185
186 static pid_t child;
187
188 static void hand_down(int signal)
189 {
190         kill(child, signal);
191 }
192
193 static void release_locks(void)
194 {
195         /* Locks were never acquired/reacquired? */
196         if (lock_owner == 0)
197                 return;
198
199         /* We own them?  Release them all. */
200         if (lock_owner == getpid()) {
201                 unsigned int i;
202                 struct flock fl;
203                 fl.l_type = F_UNLCK;
204                 fl.l_whence = SEEK_SET;
205                 fl.l_start = 0;
206                 fl.l_len = 0;
207
208                 for (i = 0; i < lock_num; i++)
209                         fcntl(locks[i].fd, F_SETLK, &fl);
210         } else {
211                 /* Our parent must have them; pass request up. */
212                 enum info_type type = RELEASE_LOCKS;
213                 assert(control_fd != -1);
214                 write_all(control_fd, &type, sizeof(type));
215         }
216         lock_owner = 0;
217 }
218
219 /* off_t is a signed type.  Getting its max is non-trivial. */
220 static off_t off_max(void)
221 {
222         BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
223         if (sizeof(off_t) == 4)
224                 return (off_t)0x7FFFFFF;
225         else
226                 return (off_t)0x7FFFFFFFFFFFFFFULL;
227 }
228
229 static void get_locks(void)
230 {
231         unsigned int i;
232         struct flock fl;
233
234         if (lock_owner == getpid())
235                 return;
236
237         if (lock_owner != 0) {
238                 enum info_type type = RELEASE_LOCKS;
239                 assert(control_fd != -1);
240                 write_all(control_fd, &type, sizeof(type));
241         }
242
243         fl.l_whence = SEEK_SET;
244
245         for (i = 0; i < lock_num; i++) {
246                 fl.l_type = locks[i].type;
247                 fl.l_start = locks[i].start;
248                 if (locks[i].end == off_max())
249                         fl.l_len = 0;
250                 else
251                         fl.l_len = locks[i].end - locks[i].start + 1;
252
253                 if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
254                         abort();
255         }
256         lock_owner = getpid();
257 }
258
259 static void trace_str(const char *str)
260 {
261         ssize_t ret;
262
263         while ((ret = write(tracefd, str, strlen(str))) <= 0) {
264                 str += ret;
265                 if (!*str)
266                         return;
267         }
268         err(1, "Writing trace.");
269 }
270
271 static bool should_fail(struct failtest_call *call)
272 {
273         int status;
274         int control[2], output[2];
275         enum info_type type = UNEXPECTED;
276         char *out = NULL;
277         size_t outlen = 0;
278
279         if (call == &unrecorded_call)
280                 return false;
281
282         if (failpath) {
283                 if (tolower(*failpath) != info_to_arg[call->type])
284                         errx(1, "Failpath expected '%c' got '%c'\n",
285                              info_to_arg[call->type], *failpath);
286                 call->fail = isupper(*(failpath++));
287                 return call->fail;
288         }
289
290         if (!failtest_hook(history, history_num)) {
291                 call->fail = false;
292                 return false;
293         }
294
295         /* We're going to fail in the child. */
296         call->fail = true;
297         if (pipe(control) != 0 || pipe(output) != 0)
298                 err(1, "opening pipe");
299
300         /* Prevent double-printing (in child and parent) */
301         fflush(stdout);
302         child = fork();
303         if (child == -1)
304                 err(1, "forking failed");
305
306         if (child == 0) {
307                 if (tracefd != -1) {
308                         struct timeval now;
309                         char str[50], *p;
310                         gettimeofday(&now, NULL);
311                         if (now.tv_usec < start.tv_usec) {
312                                 now.tv_sec--;
313                                 now.tv_usec += 1000000;
314                         }
315                         now.tv_usec -= start.tv_usec;
316                         now.tv_sec -= start.tv_sec;
317                         sprintf(str, "%u (%u.%02u): ", getpid(),
318                                 (int)now.tv_sec, (int)now.tv_usec / 10000);
319                         trace_str(str);
320                         p = failpath_string();
321                         trace_str(p);
322                         free(p);
323                         trace_str("(");
324                         p = strchr(history[history_num-1].file, '/');
325                         if (p)
326                                 trace_str(p+1);
327                         else
328                                 trace_str(history[history_num-1].file);
329                         sprintf(str, ":%u)\n", history[history_num-1].line);
330                         trace_str(str);
331                 }
332                 close(control[0]);
333                 close(output[0]);
334                 dup2(output[1], STDOUT_FILENO);
335                 dup2(output[1], STDERR_FILENO);
336                 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
337                         close(output[1]);
338                 control_fd = control[1];
339                 return true;
340         }
341
342         signal(SIGUSR1, hand_down);
343
344         close(control[1]);
345         close(output[1]);
346
347         /* We grab output so we can display it; we grab writes so we
348          * can compare. */
349         do {
350                 struct pollfd pfd[2];
351                 int ret;
352
353                 pfd[0].fd = output[0];
354                 pfd[0].events = POLLIN|POLLHUP;
355                 pfd[1].fd = control[0];
356                 pfd[1].events = POLLIN|POLLHUP;
357
358                 if (type == SUCCESS)
359                         ret = poll(pfd, 1, failtest_timeout_ms);
360                 else
361                         ret = poll(pfd, 2, failtest_timeout_ms);
362
363                 if (ret <= 0)
364                         hand_down(SIGUSR1);
365
366                 if (pfd[0].revents & POLLIN) {
367                         ssize_t len;
368
369                         out = realloc(out, outlen + 8192);
370                         len = read(output[0], out + outlen, 8192);
371                         outlen += len;
372                 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
373                         if (read_all(control[0], &type, sizeof(type))) {
374                                 if (type == WRITE) {
375                                         if (!read_write_info(control[0]))
376                                                 break;
377                                 } else if (type == RELEASE_LOCKS) {
378                                         release_locks();
379                                         /* FIXME: Tell them we're done... */
380                                 }
381                         }
382                 } else if (pfd[0].revents & POLLHUP) {
383                         break;
384                 }
385         } while (type != FAILURE);
386
387         close(output[0]);
388         close(control[0]);
389         waitpid(child, &status, 0);
390         if (!WIFEXITED(status))
391                 child_fail(out, outlen, "Killed by signal %u: ",
392                            WTERMSIG(status));
393         /* Child printed failure already, just pass up exit code. */
394         if (type == FAILURE) {
395                 fprintf(stderr, "%.*s", (int)outlen, out);
396                 tell_parent(type);
397                 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
398         }
399         if (WEXITSTATUS(status) != 0)
400                 child_fail(out, outlen, "Exited with status %i: ",
401                            WEXITSTATUS(status));
402
403         free(out);
404         signal(SIGUSR1, SIG_DFL);
405
406         /* We continue onwards without failing. */
407         call->fail = false;
408         return false;
409 }
410
411 void *failtest_calloc(size_t nmemb, size_t size,
412                       const char *file, unsigned line)
413 {
414         struct failtest_call *p;
415         struct calloc_call call;
416         call.nmemb = nmemb;
417         call.size = size;
418         p = add_history(FAILTEST_CALLOC, file, line, &call);
419
420         if (should_fail(p)) {
421                 p->u.calloc.ret = NULL;
422                 p->error = ENOMEM;
423         } else {
424                 p->u.calloc.ret = calloc(nmemb, size);
425         }
426         errno = p->error;
427         return p->u.calloc.ret;
428 }
429
430 void *failtest_malloc(size_t size, const char *file, unsigned line)
431 {
432         struct failtest_call *p;
433         struct malloc_call call;
434         call.size = size;
435
436         p = add_history(FAILTEST_MALLOC, file, line, &call);
437         if (should_fail(p)) {
438                 p->u.calloc.ret = NULL;
439                 p->error = ENOMEM;
440         } else {
441                 p->u.calloc.ret = malloc(size);
442         }
443         errno = p->error;
444         return p->u.calloc.ret;
445 }
446
447 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
448 {
449         struct failtest_call *p;
450         struct realloc_call call;
451         call.size = size;
452         p = add_history(FAILTEST_REALLOC, file, line, &call);
453
454         /* FIXME: Try one child moving allocation, one not. */
455         if (should_fail(p)) {
456                 p->u.realloc.ret = NULL;
457                 p->error = ENOMEM;
458         } else {
459                 p->u.realloc.ret = realloc(ptr, size);
460         }
461         errno = p->error;
462         return p->u.realloc.ret;
463 }
464
465 int failtest_open(const char *pathname,
466                   const char *file, unsigned line, ...)
467 {
468         struct failtest_call *p;
469         struct open_call call;
470         va_list ap;
471
472         call.pathname = strdup(pathname);
473         va_start(ap, line);
474         call.flags = va_arg(ap, int);
475         if (call.flags & O_CREAT) {
476                 call.mode = va_arg(ap, mode_t);
477                 va_end(ap);
478         }
479         p = add_history(FAILTEST_OPEN, file, line, &call);
480         /* Avoid memory leak! */
481         if (p == &unrecorded_call)
482                 free((char *)call.pathname);
483         if (should_fail(p)) {
484                 p->u.open.ret = -1;
485                 /* FIXME: Play with error codes? */
486                 p->error = EACCES;
487         } else {
488                 p->u.open.ret = open(pathname, call.flags, call.mode);
489         }
490         errno = p->error;
491         return p->u.open.ret;
492 }
493
494 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
495 {
496         struct failtest_call *p;
497         struct pipe_call call;
498
499         p = add_history(FAILTEST_PIPE, file, line, &call);
500         if (should_fail(p)) {
501                 p->u.open.ret = -1;
502                 /* FIXME: Play with error codes? */
503                 p->error = EMFILE;
504         } else {
505                 p->u.pipe.ret = pipe(p->u.pipe.fds);
506         }
507         /* This causes valgrind to notice if they use pipefd[] after failure */
508         memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
509         errno = p->error;
510         return p->u.pipe.ret;
511 }
512
513 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
514                        const char *file, unsigned line)
515 {
516         struct failtest_call *p;
517         struct read_call call;
518         call.fd = fd;
519         call.buf = buf;
520         call.count = count;
521         call.off = off;
522         p = add_history(FAILTEST_READ, file, line, &call);
523
524         /* This is going to change seek offset, so save it. */
525         if (control_fd != -1)
526                 save_fd_orig(fd);
527
528         /* FIXME: Try partial read returns. */
529         if (should_fail(p)) {
530                 p->u.read.ret = -1;
531                 p->error = EIO;
532         } else {
533                 p->u.read.ret = pread(fd, buf, count, off);
534         }
535         errno = p->error;
536         return p->u.read.ret;
537 }
538
539 static struct write_info *new_write(void)
540 {
541         writes = realloc(writes, (writes_num + 1) * sizeof(*writes));
542         return &writes[writes_num++];
543 }
544
545 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
546                         const char *file, unsigned line)
547 {
548         struct failtest_call *p;
549         struct write_call call;
550         off_t offset;
551
552         call.fd = fd;
553         call.buf = buf;
554         call.count = count;
555         call.off = off;
556         p = add_history(FAILTEST_WRITE, file, line, &call);
557
558         offset = lseek(fd, 0, SEEK_CUR);
559
560         /* If we're a child, save contents and tell parent about write. */
561         if (control_fd != -1) {
562                 struct write_info *winfo = new_write();
563                 enum info_type type = WRITE;
564
565                 save_fd_orig(fd);
566
567                 winfo->hdr.len = count;
568                 winfo->hdr.fd = fd;
569                 winfo->data = malloc(count);
570                 memcpy(winfo->data, buf, count);
571                 winfo->hdr.offset = offset;
572                 if (winfo->hdr.offset != (off_t)-1) {
573                         lseek(fd, offset, SEEK_SET);
574                         winfo->olddata = malloc(count);
575                         winfo->oldlen = read(fd, winfo->olddata, count);
576                         if (winfo->oldlen == -1)
577                                 winfo->oldlen = 0;
578                 }
579                 write_all(control_fd, &type, sizeof(type));
580                 write_all(control_fd, &winfo->hdr, sizeof(winfo->hdr));
581                 write_all(control_fd, winfo->data, count);
582         }
583
584         /* FIXME: Try partial write returns. */
585         if (should_fail(p)) {
586                 p->u.write.ret = -1;
587                 p->error = EIO;
588         } else {
589                 /* FIXME: We assume same write order in parent and child */
590                 if (child_writes_num != 0) {
591                         if (child_writes[0].hdr.fd != fd)
592                                 errx(1, "Child wrote to fd %u, not %u?",
593                                      child_writes[0].hdr.fd, fd);
594                         if (child_writes[0].hdr.offset != offset)
595                                 errx(1, "Child wrote to offset %zu, not %zu?",
596                                      (size_t)child_writes[0].hdr.offset,
597                                      (size_t)offset);
598                         if (child_writes[0].hdr.len != count)
599                                 errx(1, "Child wrote length %zu, not %zu?",
600                                      child_writes[0].hdr.len, count);
601                         if (memcmp(child_writes[0].data, buf, count)) {
602                                 child_fail(NULL, 0,
603                                            "Child wrote differently to"
604                                            " fd %u than we did!\n", fd);
605                         }
606                         free(child_writes[0].data);
607                         child_writes_num--;
608                         memmove(&child_writes[0], &child_writes[1],
609                                 sizeof(child_writes[0]) * child_writes_num);
610
611                         /* Is this is a socket or pipe, child wrote it
612                            already. */
613                         if (offset == (off_t)-1) {
614                                 p->u.write.ret = count;
615                                 errno = p->error;
616                                 return p->u.write.ret;
617                         }
618                 }
619                 p->u.write.ret = pwrite(fd, buf, count, off);
620         }
621         errno = p->error;
622         return p->u.write.ret;
623 }
624
625 ssize_t failtest_read(int fd, void *buf, size_t count,
626                       const char *file, unsigned line)
627 {
628         return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
629                               file, line);
630 }
631
632 ssize_t failtest_write(int fd, const void *buf, size_t count,
633                        const char *file, unsigned line)
634 {
635         return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
636                                file, line);
637 }
638
639 static struct lock_info *WARN_UNUSED_RESULT
640 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
641 {
642         unsigned int i;
643         struct lock_info *l;
644
645         for (i = 0; i < lock_num; i++) {
646                 l = &locks[i];
647
648                 if (l->fd != fd)
649                         continue;
650                 /* Four cases we care about:
651                  * Start overlap:
652                  *      l =    |      |
653                  *      new = |   |
654                  * Mid overlap:
655                  *      l =    |      |
656                  *      new =    |  |
657                  * End overlap:
658                  *      l =    |      |
659                  *      new =      |    |
660                  * Total overlap:
661                  *      l =    |      |
662                  *      new = |         |
663                  */
664                 if (start > l->start && end < l->end) {
665                         /* Mid overlap: trim entry, add new one. */
666                         off_t new_start, new_end;
667                         new_start = end + 1;
668                         new_end = l->end;
669                         l->end = start - 1;
670                         locks = add_lock(locks,
671                                          fd, new_start, new_end, l->type);
672                         l = &locks[i];
673                 } else if (start <= l->start && end >= l->end) {
674                         /* Total overlap: eliminate entry. */
675                         l->end = 0;
676                         l->start = 1;
677                 } else if (end >= l->start && end < l->end) {
678                         /* Start overlap: trim entry. */
679                         l->start = end + 1;
680                 } else if (start > l->start && start <= l->end) {
681                         /* End overlap: trim entry. */
682                         l->end = start-1;
683                 }
684                 /* Nothing left?  Remove it. */
685                 if (l->end < l->start) {
686                         memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
687                         i--;
688                 }
689         }
690
691         if (type != F_UNLCK) {
692                 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
693                 l = &locks[lock_num++];
694                 l->fd = fd;
695                 l->start = start;
696                 l->end = end;
697                 l->type = type;
698         }
699         return locks;
700 }
701
702 /* We only trap this so we can dup fds in case we need to restore. */
703 int failtest_close(int fd)
704 {
705         unsigned int i;
706         int newfd = -1;
707
708         for (i = 0; i < fd_orig_num; i++) {
709                 if (fd_orig[i].fd == fd) {
710                         fd_orig[i].fd = newfd = dup(fd);
711                         fd_orig[i].dupped = true;
712                 }
713         }
714
715         for (i = 0; i < writes_num; i++) {
716                 if (writes[i].hdr.fd == fd)
717                         writes[i].hdr.fd = newfd;
718         }
719
720         locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
721         return close(fd);
722 }
723
724 /* Zero length means "to end of file" */
725 static off_t end_of(off_t start, off_t len)
726 {
727         if (len == 0)
728                 return off_max();
729         return start + len - 1;
730 }
731
732 /* FIXME: This only handles locks, really. */
733 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
734 {
735         struct failtest_call *p;
736         struct fcntl_call call;
737         va_list ap;
738
739         call.fd = fd;
740         call.cmd = cmd;
741
742         /* Argument extraction. */
743         switch (cmd) {
744         case F_SETFL:
745         case F_SETFD:
746                 va_start(ap, cmd);
747                 call.arg.l = va_arg(ap, long);
748                 va_end(ap);
749                 return fcntl(fd, cmd, call.arg.l);
750         case F_GETFD:
751         case F_GETFL:
752                 return fcntl(fd, cmd);
753         case F_GETLK:
754                 get_locks();
755                 va_start(ap, cmd);
756                 call.arg.fl = *va_arg(ap, struct flock *);
757                 va_end(ap);
758                 return fcntl(fd, cmd, &call.arg.fl);
759         case F_SETLK:
760         case F_SETLKW:
761                 va_start(ap, cmd);
762                 call.arg.fl = *va_arg(ap, struct flock *);
763                 va_end(ap);
764                 break;
765         default:
766                 /* This means you need to implement it here. */
767                 err(1, "failtest: unknown fcntl %u", cmd);
768         }
769
770         p = add_history(FAILTEST_FCNTL, file, line, &call);
771         get_locks();
772
773         if (should_fail(p)) {
774                 p->u.fcntl.ret = -1;
775                 if (p->u.fcntl.cmd == F_SETLK)
776                         p->error = EAGAIN;
777                 else
778                         p->error = EDEADLK;
779         } else {
780                 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
781                                        &p->u.fcntl.arg.fl);
782                 if (p->u.fcntl.ret == -1)
783                         p->error = errno;
784                 else {
785                         /* We don't handle anything else yet. */
786                         assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
787                         locks = add_lock(locks,
788                                          p->u.fcntl.fd,
789                                          p->u.fcntl.arg.fl.l_start,
790                                          end_of(p->u.fcntl.arg.fl.l_start,
791                                                 p->u.fcntl.arg.fl.l_len),
792                                          p->u.fcntl.arg.fl.l_type);
793                 }
794         }
795         errno = p->error;
796         return p->u.fcntl.ret;
797 }
798
799 void failtest_init(int argc, char *argv[])
800 {
801         unsigned int i;
802
803         for (i = 1; i < argc; i++) {
804                 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
805                         failpath = argv[i] + strlen("--failpath=");
806                 } else if (strcmp(argv[i], "--tracepath") == 0) {
807                         tracefd = dup(STDERR_FILENO);
808                         failtest_timeout_ms = -1;
809                 }
810         }
811         gettimeofday(&start, NULL);
812 }
813
814 /* Free up memory, so valgrind doesn't report leaks. */
815 static void free_everything(void)
816 {
817         unsigned int i;
818
819         for (i = 0; i < writes_num; i++) {
820                 free(writes[i].data);
821                 if (writes[i].hdr.offset != (off_t)-1)
822                         free(writes[i].olddata);
823         }
824         free(writes);
825         free(fd_orig);
826         for (i = 0; i < history_num; i++) {
827                 if (history[i].type == FAILTEST_OPEN)
828                         free((char *)history[i].u.open.pathname);
829         }
830         free(history);
831 }
832
833 void failtest_exit(int status)
834 {
835         unsigned int i;
836
837         if (control_fd == -1) {
838                 free_everything();
839                 exit(status);
840         }
841
842         if (failtest_exit_check) {
843                 if (!failtest_exit_check(history, history_num))
844                         child_fail(NULL, 0, "failtest_exit_check failed\n");
845         }
846
847         /* Restore any stuff we overwrote. */
848         for (i = 0; i < writes_num; i++) {
849                 if (writes[i].hdr.offset == (off_t)-1)
850                         continue;
851                 if (writes[i].oldlen != 0) {
852                         lseek(writes[i].hdr.fd, writes[i].hdr.offset,
853                               SEEK_SET);
854                         write(writes[i].hdr.fd, writes[i].olddata,
855                               writes[i].oldlen);
856                 }
857         }
858
859         /* Fix up fd offsets, restore sizes. */
860         for (i = 0; i < fd_orig_num; i++) {
861                 lseek(fd_orig[i].fd, fd_orig[i].offset, SEEK_SET);
862                 ftruncate(fd_orig[i].fd, fd_orig[i].size);
863                 /* Free up any file descriptors we dup'ed. */
864                 if (fd_orig[i].dupped)
865                         close(fd_orig[i].fd);
866         }
867
868         free_everything();
869         tell_parent(SUCCESS);
870         exit(0);
871 }