]> git.ozlabs.org Git - ccan/blob - ccan/failtest/failtest.c
4f71a63dc172896928cde965277b145093c13869
[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                 /* + means continue after end, like normal. */
284                 if (*failpath == '+')
285                         failpath = NULL;
286                 else {
287                         if (tolower(*failpath) != info_to_arg[call->type])
288                                 errx(1, "Failpath expected '%c' got '%c'\n",
289                                      info_to_arg[call->type], *failpath);
290                         call->fail = isupper(*(failpath++));
291                         return call->fail;
292                 }
293         }
294
295         if (!failtest_hook(history, history_num)) {
296                 call->fail = false;
297                 return false;
298         }
299
300         /* We're going to fail in the child. */
301         call->fail = true;
302         if (pipe(control) != 0 || pipe(output) != 0)
303                 err(1, "opening pipe");
304
305         /* Prevent double-printing (in child and parent) */
306         fflush(stdout);
307         child = fork();
308         if (child == -1)
309                 err(1, "forking failed");
310
311         if (child == 0) {
312                 if (tracefd != -1) {
313                         struct timeval now;
314                         char str[50], *p;
315                         gettimeofday(&now, NULL);
316                         if (now.tv_usec < start.tv_usec) {
317                                 now.tv_sec--;
318                                 now.tv_usec += 1000000;
319                         }
320                         now.tv_usec -= start.tv_usec;
321                         now.tv_sec -= start.tv_sec;
322                         sprintf(str, "%u (%u.%02u): ", getpid(),
323                                 (int)now.tv_sec, (int)now.tv_usec / 10000);
324                         trace_str(str);
325                         p = failpath_string();
326                         trace_str(p);
327                         free(p);
328                         trace_str("(");
329                         p = strchr(history[history_num-1].file, '/');
330                         if (p)
331                                 trace_str(p+1);
332                         else
333                                 trace_str(history[history_num-1].file);
334                         sprintf(str, ":%u)\n", history[history_num-1].line);
335                         trace_str(str);
336                 }
337                 close(control[0]);
338                 close(output[0]);
339                 dup2(output[1], STDOUT_FILENO);
340                 dup2(output[1], STDERR_FILENO);
341                 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
342                         close(output[1]);
343                 control_fd = control[1];
344                 return true;
345         }
346
347         signal(SIGUSR1, hand_down);
348
349         close(control[1]);
350         close(output[1]);
351
352         /* We grab output so we can display it; we grab writes so we
353          * can compare. */
354         do {
355                 struct pollfd pfd[2];
356                 int ret;
357
358                 pfd[0].fd = output[0];
359                 pfd[0].events = POLLIN|POLLHUP;
360                 pfd[1].fd = control[0];
361                 pfd[1].events = POLLIN|POLLHUP;
362
363                 if (type == SUCCESS)
364                         ret = poll(pfd, 1, failtest_timeout_ms);
365                 else
366                         ret = poll(pfd, 2, failtest_timeout_ms);
367
368                 if (ret <= 0)
369                         hand_down(SIGUSR1);
370
371                 if (pfd[0].revents & POLLIN) {
372                         ssize_t len;
373
374                         out = realloc(out, outlen + 8192);
375                         len = read(output[0], out + outlen, 8192);
376                         outlen += len;
377                 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
378                         if (read_all(control[0], &type, sizeof(type))) {
379                                 if (type == WRITE) {
380                                         if (!read_write_info(control[0]))
381                                                 break;
382                                 } else if (type == RELEASE_LOCKS) {
383                                         release_locks();
384                                         /* FIXME: Tell them we're done... */
385                                 }
386                         }
387                 } else if (pfd[0].revents & POLLHUP) {
388                         break;
389                 }
390         } while (type != FAILURE);
391
392         close(output[0]);
393         close(control[0]);
394         waitpid(child, &status, 0);
395         if (!WIFEXITED(status))
396                 child_fail(out, outlen, "Killed by signal %u: ",
397                            WTERMSIG(status));
398         /* Child printed failure already, just pass up exit code. */
399         if (type == FAILURE) {
400                 fprintf(stderr, "%.*s", (int)outlen, out);
401                 tell_parent(type);
402                 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
403         }
404         if (WEXITSTATUS(status) != 0)
405                 child_fail(out, outlen, "Exited with status %i: ",
406                            WEXITSTATUS(status));
407
408         free(out);
409         signal(SIGUSR1, SIG_DFL);
410
411         /* We continue onwards without failing. */
412         call->fail = false;
413         return false;
414 }
415
416 void *failtest_calloc(size_t nmemb, size_t size,
417                       const char *file, unsigned line)
418 {
419         struct failtest_call *p;
420         struct calloc_call call;
421         call.nmemb = nmemb;
422         call.size = size;
423         p = add_history(FAILTEST_CALLOC, file, line, &call);
424
425         if (should_fail(p)) {
426                 p->u.calloc.ret = NULL;
427                 p->error = ENOMEM;
428         } else {
429                 p->u.calloc.ret = calloc(nmemb, size);
430         }
431         errno = p->error;
432         return p->u.calloc.ret;
433 }
434
435 void *failtest_malloc(size_t size, const char *file, unsigned line)
436 {
437         struct failtest_call *p;
438         struct malloc_call call;
439         call.size = size;
440
441         p = add_history(FAILTEST_MALLOC, file, line, &call);
442         if (should_fail(p)) {
443                 p->u.calloc.ret = NULL;
444                 p->error = ENOMEM;
445         } else {
446                 p->u.calloc.ret = malloc(size);
447         }
448         errno = p->error;
449         return p->u.calloc.ret;
450 }
451
452 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
453 {
454         struct failtest_call *p;
455         struct realloc_call call;
456         call.size = size;
457         p = add_history(FAILTEST_REALLOC, file, line, &call);
458
459         /* FIXME: Try one child moving allocation, one not. */
460         if (should_fail(p)) {
461                 p->u.realloc.ret = NULL;
462                 p->error = ENOMEM;
463         } else {
464                 p->u.realloc.ret = realloc(ptr, size);
465         }
466         errno = p->error;
467         return p->u.realloc.ret;
468 }
469
470 int failtest_open(const char *pathname,
471                   const char *file, unsigned line, ...)
472 {
473         struct failtest_call *p;
474         struct open_call call;
475         va_list ap;
476
477         call.pathname = strdup(pathname);
478         va_start(ap, line);
479         call.flags = va_arg(ap, int);
480         if (call.flags & O_CREAT) {
481                 call.mode = va_arg(ap, mode_t);
482                 va_end(ap);
483         }
484         p = add_history(FAILTEST_OPEN, file, line, &call);
485         /* Avoid memory leak! */
486         if (p == &unrecorded_call)
487                 free((char *)call.pathname);
488         if (should_fail(p)) {
489                 p->u.open.ret = -1;
490                 /* FIXME: Play with error codes? */
491                 p->error = EACCES;
492         } else {
493                 p->u.open.ret = open(pathname, call.flags, call.mode);
494         }
495         errno = p->error;
496         return p->u.open.ret;
497 }
498
499 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
500 {
501         struct failtest_call *p;
502         struct pipe_call call;
503
504         p = add_history(FAILTEST_PIPE, file, line, &call);
505         if (should_fail(p)) {
506                 p->u.open.ret = -1;
507                 /* FIXME: Play with error codes? */
508                 p->error = EMFILE;
509         } else {
510                 p->u.pipe.ret = pipe(p->u.pipe.fds);
511         }
512         /* This causes valgrind to notice if they use pipefd[] after failure */
513         memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
514         errno = p->error;
515         return p->u.pipe.ret;
516 }
517
518 ssize_t failtest_pread(int fd, void *buf, size_t count, off_t off,
519                        const char *file, unsigned line)
520 {
521         struct failtest_call *p;
522         struct read_call call;
523         call.fd = fd;
524         call.buf = buf;
525         call.count = count;
526         call.off = off;
527         p = add_history(FAILTEST_READ, file, line, &call);
528
529         /* This is going to change seek offset, so save it. */
530         if (control_fd != -1)
531                 save_fd_orig(fd);
532
533         /* FIXME: Try partial read returns. */
534         if (should_fail(p)) {
535                 p->u.read.ret = -1;
536                 p->error = EIO;
537         } else {
538                 p->u.read.ret = pread(fd, buf, count, off);
539         }
540         errno = p->error;
541         return p->u.read.ret;
542 }
543
544 static struct write_info *new_write(void)
545 {
546         writes = realloc(writes, (writes_num + 1) * sizeof(*writes));
547         return &writes[writes_num++];
548 }
549
550 ssize_t failtest_pwrite(int fd, const void *buf, size_t count, off_t off,
551                         const char *file, unsigned line)
552 {
553         struct failtest_call *p;
554         struct write_call call;
555         off_t offset;
556
557         call.fd = fd;
558         call.buf = buf;
559         call.count = count;
560         call.off = off;
561         p = add_history(FAILTEST_WRITE, file, line, &call);
562
563         offset = lseek(fd, 0, SEEK_CUR);
564
565         /* If we're a child, save contents and tell parent about write. */
566         if (control_fd != -1) {
567                 struct write_info *winfo = new_write();
568                 enum info_type type = WRITE;
569
570                 save_fd_orig(fd);
571
572                 winfo->hdr.len = count;
573                 winfo->hdr.fd = fd;
574                 winfo->data = malloc(count);
575                 memcpy(winfo->data, buf, count);
576                 winfo->hdr.offset = offset;
577                 if (winfo->hdr.offset != (off_t)-1) {
578                         lseek(fd, offset, SEEK_SET);
579                         winfo->olddata = malloc(count);
580                         winfo->oldlen = read(fd, winfo->olddata, count);
581                         if (winfo->oldlen == -1)
582                                 winfo->oldlen = 0;
583                 }
584                 write_all(control_fd, &type, sizeof(type));
585                 write_all(control_fd, &winfo->hdr, sizeof(winfo->hdr));
586                 write_all(control_fd, winfo->data, count);
587         }
588
589         /* FIXME: Try partial write returns. */
590         if (should_fail(p)) {
591                 p->u.write.ret = -1;
592                 p->error = EIO;
593         } else {
594                 /* FIXME: We assume same write order in parent and child */
595                 if (child_writes_num != 0) {
596                         if (child_writes[0].hdr.fd != fd)
597                                 errx(1, "Child wrote to fd %u, not %u?",
598                                      child_writes[0].hdr.fd, fd);
599                         if (child_writes[0].hdr.offset != offset)
600                                 errx(1, "Child wrote to offset %zu, not %zu?",
601                                      (size_t)child_writes[0].hdr.offset,
602                                      (size_t)offset);
603                         if (child_writes[0].hdr.len != count)
604                                 errx(1, "Child wrote length %zu, not %zu?",
605                                      child_writes[0].hdr.len, count);
606                         if (memcmp(child_writes[0].data, buf, count)) {
607                                 child_fail(NULL, 0,
608                                            "Child wrote differently to"
609                                            " fd %u than we did!\n", fd);
610                         }
611                         free(child_writes[0].data);
612                         child_writes_num--;
613                         memmove(&child_writes[0], &child_writes[1],
614                                 sizeof(child_writes[0]) * child_writes_num);
615
616                         /* Is this is a socket or pipe, child wrote it
617                            already. */
618                         if (offset == (off_t)-1) {
619                                 p->u.write.ret = count;
620                                 errno = p->error;
621                                 return p->u.write.ret;
622                         }
623                 }
624                 p->u.write.ret = pwrite(fd, buf, count, off);
625         }
626         errno = p->error;
627         return p->u.write.ret;
628 }
629
630 ssize_t failtest_read(int fd, void *buf, size_t count,
631                       const char *file, unsigned line)
632 {
633         return failtest_pread(fd, buf, count, lseek(fd, 0, SEEK_CUR),
634                               file, line);
635 }
636
637 ssize_t failtest_write(int fd, const void *buf, size_t count,
638                        const char *file, unsigned line)
639 {
640         return failtest_pwrite(fd, buf, count, lseek(fd, 0, SEEK_CUR),
641                                file, line);
642 }
643
644 static struct lock_info *WARN_UNUSED_RESULT
645 add_lock(struct lock_info *locks, int fd, off_t start, off_t end, int type)
646 {
647         unsigned int i;
648         struct lock_info *l;
649
650         for (i = 0; i < lock_num; i++) {
651                 l = &locks[i];
652
653                 if (l->fd != fd)
654                         continue;
655                 /* Four cases we care about:
656                  * Start overlap:
657                  *      l =    |      |
658                  *      new = |   |
659                  * Mid overlap:
660                  *      l =    |      |
661                  *      new =    |  |
662                  * End overlap:
663                  *      l =    |      |
664                  *      new =      |    |
665                  * Total overlap:
666                  *      l =    |      |
667                  *      new = |         |
668                  */
669                 if (start > l->start && end < l->end) {
670                         /* Mid overlap: trim entry, add new one. */
671                         off_t new_start, new_end;
672                         new_start = end + 1;
673                         new_end = l->end;
674                         l->end = start - 1;
675                         locks = add_lock(locks,
676                                          fd, new_start, new_end, l->type);
677                         l = &locks[i];
678                 } else if (start <= l->start && end >= l->end) {
679                         /* Total overlap: eliminate entry. */
680                         l->end = 0;
681                         l->start = 1;
682                 } else if (end >= l->start && end < l->end) {
683                         /* Start overlap: trim entry. */
684                         l->start = end + 1;
685                 } else if (start > l->start && start <= l->end) {
686                         /* End overlap: trim entry. */
687                         l->end = start-1;
688                 }
689                 /* Nothing left?  Remove it. */
690                 if (l->end < l->start) {
691                         memmove(l, l + 1, (--lock_num - i) * sizeof(l[0]));
692                         i--;
693                 }
694         }
695
696         if (type != F_UNLCK) {
697                 locks = realloc(locks, (lock_num + 1) * sizeof(*locks));
698                 l = &locks[lock_num++];
699                 l->fd = fd;
700                 l->start = start;
701                 l->end = end;
702                 l->type = type;
703         }
704         return locks;
705 }
706
707 /* We only trap this so we can dup fds in case we need to restore. */
708 int failtest_close(int fd)
709 {
710         unsigned int i;
711         int newfd = -1;
712
713         for (i = 0; i < fd_orig_num; i++) {
714                 if (fd_orig[i].fd == fd) {
715                         fd_orig[i].fd = newfd = dup(fd);
716                         fd_orig[i].dupped = true;
717                 }
718         }
719
720         for (i = 0; i < writes_num; i++) {
721                 if (writes[i].hdr.fd == fd)
722                         writes[i].hdr.fd = newfd;
723         }
724
725         locks = add_lock(locks, fd, 0, off_max(), F_UNLCK);
726         return close(fd);
727 }
728
729 /* Zero length means "to end of file" */
730 static off_t end_of(off_t start, off_t len)
731 {
732         if (len == 0)
733                 return off_max();
734         return start + len - 1;
735 }
736
737 /* FIXME: This only handles locks, really. */
738 int failtest_fcntl(int fd, const char *file, unsigned line, int cmd, ...)
739 {
740         struct failtest_call *p;
741         struct fcntl_call call;
742         va_list ap;
743
744         call.fd = fd;
745         call.cmd = cmd;
746
747         /* Argument extraction. */
748         switch (cmd) {
749         case F_SETFL:
750         case F_SETFD:
751                 va_start(ap, cmd);
752                 call.arg.l = va_arg(ap, long);
753                 va_end(ap);
754                 return fcntl(fd, cmd, call.arg.l);
755         case F_GETFD:
756         case F_GETFL:
757                 return fcntl(fd, cmd);
758         case F_GETLK:
759                 get_locks();
760                 va_start(ap, cmd);
761                 call.arg.fl = *va_arg(ap, struct flock *);
762                 va_end(ap);
763                 return fcntl(fd, cmd, &call.arg.fl);
764         case F_SETLK:
765         case F_SETLKW:
766                 va_start(ap, cmd);
767                 call.arg.fl = *va_arg(ap, struct flock *);
768                 va_end(ap);
769                 break;
770         default:
771                 /* This means you need to implement it here. */
772                 err(1, "failtest: unknown fcntl %u", cmd);
773         }
774
775         p = add_history(FAILTEST_FCNTL, file, line, &call);
776         get_locks();
777
778         if (should_fail(p)) {
779                 p->u.fcntl.ret = -1;
780                 if (p->u.fcntl.cmd == F_SETLK)
781                         p->error = EAGAIN;
782                 else
783                         p->error = EDEADLK;
784         } else {
785                 p->u.fcntl.ret = fcntl(p->u.fcntl.fd, p->u.fcntl.cmd,
786                                        &p->u.fcntl.arg.fl);
787                 if (p->u.fcntl.ret == -1)
788                         p->error = errno;
789                 else {
790                         /* We don't handle anything else yet. */
791                         assert(p->u.fcntl.arg.fl.l_whence == SEEK_SET);
792                         locks = add_lock(locks,
793                                          p->u.fcntl.fd,
794                                          p->u.fcntl.arg.fl.l_start,
795                                          end_of(p->u.fcntl.arg.fl.l_start,
796                                                 p->u.fcntl.arg.fl.l_len),
797                                          p->u.fcntl.arg.fl.l_type);
798                 }
799         }
800         errno = p->error;
801         return p->u.fcntl.ret;
802 }
803
804 void failtest_init(int argc, char *argv[])
805 {
806         unsigned int i;
807
808         for (i = 1; i < argc; i++) {
809                 if (!strncmp(argv[i], "--failpath=", strlen("--failpath="))) {
810                         failpath = argv[i] + strlen("--failpath=");
811                 } else if (strcmp(argv[i], "--tracepath") == 0) {
812                         tracefd = dup(STDERR_FILENO);
813                         failtest_timeout_ms = -1;
814                 }
815         }
816         gettimeofday(&start, NULL);
817 }
818
819 /* Free up memory, so valgrind doesn't report leaks. */
820 static void free_everything(void)
821 {
822         unsigned int i;
823
824         for (i = 0; i < writes_num; i++) {
825                 free(writes[i].data);
826                 if (writes[i].hdr.offset != (off_t)-1)
827                         free(writes[i].olddata);
828         }
829         free(writes);
830         free(fd_orig);
831         for (i = 0; i < history_num; i++) {
832                 if (history[i].type == FAILTEST_OPEN)
833                         free((char *)history[i].u.open.pathname);
834         }
835         free(history);
836 }
837
838 void failtest_exit(int status)
839 {
840         unsigned int i;
841
842         if (control_fd == -1) {
843                 free_everything();
844                 exit(status);
845         }
846
847         if (failtest_exit_check) {
848                 if (!failtest_exit_check(history, history_num))
849                         child_fail(NULL, 0, "failtest_exit_check failed\n");
850         }
851
852         /* Restore any stuff we overwrote. */
853         for (i = 0; i < writes_num; i++) {
854                 if (writes[i].hdr.offset == (off_t)-1)
855                         continue;
856                 if (writes[i].oldlen != 0) {
857                         lseek(writes[i].hdr.fd, writes[i].hdr.offset,
858                               SEEK_SET);
859                         write(writes[i].hdr.fd, writes[i].olddata,
860                               writes[i].oldlen);
861                 }
862         }
863
864         /* Fix up fd offsets, restore sizes. */
865         for (i = 0; i < fd_orig_num; i++) {
866                 lseek(fd_orig[i].fd, fd_orig[i].offset, SEEK_SET);
867                 ftruncate(fd_orig[i].fd, fd_orig[i].size);
868                 /* Free up any file descriptors we dup'ed. */
869                 if (fd_orig[i].dupped)
870                         close(fd_orig[i].fd);
871         }
872
873         free_everything();
874         tell_parent(SUCCESS);
875         exit(0);
876 }