failtest: new module.
[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 <fcntl.h>
14 #include <ccan/read_write_all/read_write_all.h>
15 #include <ccan/failtest/failtest_proto.h>
16 #include <ccan/failtest/failtest.h>
17
18 bool (*failtest_hook)(struct failtest_call *history, unsigned num)
19 = failtest_default_hook;
20
21 unsigned int failtest_timeout_ms = 20000;
22
23 const char *failpath;
24
25 enum info_type {
26         WRITE,
27         FAILURE,
28         SUCCESS,
29         UNEXPECTED
30 };
31
32 struct write_info_hdr {
33         size_t len;
34         off_t offset;
35         int fd;
36 };
37
38 struct fd_orig {
39         int fd;
40         off_t offset;
41         size_t size;
42         bool dupped;
43 };
44
45 struct write_info {
46         struct write_info_hdr hdr;
47         char *data;
48         size_t oldlen;
49         char *olddata;
50 };
51
52 bool (*failtest_exit_check)(struct failtest_call *history, unsigned num);
53
54 static struct failtest_call *history = NULL;
55 static unsigned int history_num = 0;
56 static int control_fd = -1;
57
58 static struct write_info *writes = NULL;
59 static unsigned int writes_num = 0;
60
61 static struct write_info *child_writes = NULL;
62 static unsigned int child_writes_num = 0;
63
64 static struct fd_orig *fd_orig = NULL;
65 static unsigned int fd_orig_num = 0;
66
67 static const char info_to_arg[] = "mceoprw";
68
69 static struct failtest_call *add_history_(enum failtest_call_type type,
70                                           const char *file,
71                                           unsigned int line,
72                                           const void *elem,
73                                           size_t elem_size)
74 {
75         history = realloc(history, (history_num + 1) * sizeof(*history));
76         history[history_num].type = type;
77         history[history_num].file = file;
78         history[history_num].line = line;
79         memcpy(&history[history_num].u, elem, elem_size);
80         return &history[history_num++];
81 }
82
83 #define add_history(type, file, line, elem) \
84         add_history_((type), (file), (line), (elem), sizeof(*(elem)))
85
86 static void save_fd_orig(int fd)
87 {
88         unsigned int i;
89
90         for (i = 0; i < fd_orig_num; i++)
91                 if (fd_orig[i].fd == fd)
92                         return;
93
94         fd_orig = realloc(fd_orig, (fd_orig_num + 1) * sizeof(*fd_orig));
95         fd_orig[fd_orig_num].fd = fd;
96         fd_orig[fd_orig_num].dupped = false;
97         fd_orig[fd_orig_num].offset = lseek(fd, 0, SEEK_CUR);
98         fd_orig[fd_orig_num].size = lseek(fd, 0, SEEK_END);
99         lseek(fd, fd_orig[fd_orig_num].offset, SEEK_SET);
100         fd_orig_num++;
101 }
102
103 bool failtest_default_hook(struct failtest_call *history, unsigned num)
104 {
105         return true;
106 }
107
108 static bool read_write_info(int fd)
109 {
110         struct write_info_hdr hdr;
111
112         if (!read_all(fd, &hdr, sizeof(hdr)))
113                 return false;
114
115         child_writes = realloc(child_writes,
116                                (child_writes_num+1) * sizeof(child_writes[0]));
117         child_writes[child_writes_num].hdr = hdr;
118         child_writes[child_writes_num].data = malloc(hdr.len);
119         if (!read_all(fd, child_writes[child_writes_num].data, hdr.len))
120                 return false;
121
122         child_writes_num++;
123         return true;
124 }
125
126 static void print_reproduce(void)
127 {
128         unsigned int i;
129
130         printf("To reproduce: --failpath=");
131         for (i = 0; i < history_num; i++) {
132                 if (history[i].fail)
133                         printf("%c", toupper(info_to_arg[history[i].type]));
134                 else
135                         printf("%c", info_to_arg[history[i].type]);
136         }
137         printf("\n");
138 }
139
140 static void tell_parent(enum info_type type)
141 {
142         if (control_fd != -1)
143                 write_all(control_fd, &type, sizeof(type));
144 }
145
146 static void child_fail(const char *out, size_t outlen, const char *fmt, ...)
147 {
148         va_list ap;
149
150         va_start(ap, fmt);
151         vfprintf(stderr, fmt, ap);
152         va_end(ap);
153
154         fprintf(stderr, "%.*s", (int)outlen, out);
155         print_reproduce();
156         tell_parent(FAILURE);
157         exit(1);
158 }
159
160 static pid_t child;
161
162 static void hand_down(int signal)
163 {
164         kill(child, signal);
165 }
166
167 static bool should_fail(struct failtest_call *call)
168 {
169         int status;
170         int control[2], output[2];
171         enum info_type type = UNEXPECTED;
172         char *out = NULL;
173         size_t outlen = 0;
174
175         if (failpath) {
176                 if (tolower(*failpath) != info_to_arg[call->type])
177                         errx(1, "Failpath expected '%c' got '%c'\n",
178                              info_to_arg[call->type], *failpath);
179                 return isupper(*(failpath++));
180         }
181
182         if (!failtest_hook(history, history_num)) {
183                 call->fail = false;
184                 return false;
185         }
186
187         /* We're going to fail in the child. */
188         call->fail = true;
189         if (pipe(control) != 0 || pipe(output) != 0)
190                 err(1, "opening pipe");
191
192         /* Prevent double-printing (in child and parent) */
193         fflush(stdout);
194         child = fork();
195         if (child == -1)
196                 err(1, "forking failed");
197
198         if (child == 0) {
199                 close(control[0]);
200                 close(output[0]);
201                 dup2(output[1], STDOUT_FILENO);
202                 dup2(output[1], STDERR_FILENO);
203                 if (output[1] != STDOUT_FILENO && output[1] != STDERR_FILENO)
204                         close(output[1]);
205                 control_fd = control[1];
206                 return true;
207         }
208
209         signal(SIGUSR1, hand_down);
210
211         close(control[1]);
212         close(output[1]);
213
214         /* We grab output so we can display it; we grab writes so we
215          * can compare. */
216         do {
217                 struct pollfd pfd[2];
218                 int ret;
219
220                 pfd[0].fd = output[0];
221                 pfd[0].events = POLLIN|POLLHUP;
222                 pfd[1].fd = control[0];
223                 pfd[1].events = POLLIN|POLLHUP;
224
225                 if (type == SUCCESS)
226                         ret = poll(pfd, 1, failtest_timeout_ms);
227                 else
228                         ret = poll(pfd, 2, failtest_timeout_ms);
229
230                 if (ret <= 0)
231                         hand_down(SIGUSR1);
232
233                 if (pfd[0].revents & POLLIN) {
234                         ssize_t len;
235
236                         out = realloc(out, outlen + 8192);
237                         len = read(output[0], out + outlen, 8192);
238                         outlen += len;
239                 } else if (type != SUCCESS && (pfd[1].revents & POLLIN)) {
240                         if (read_all(control[0], &type, sizeof(type))) {
241                                 if (type == WRITE) {
242                                         if (!read_write_info(control[0]))
243                                                 break;
244                                 }
245                         }
246                 } else if (pfd[0].revents & POLLHUP) {
247                         break;
248                 }
249         } while (type != FAILURE);
250
251         close(output[0]);
252         close(control[0]);
253         waitpid(child, &status, 0);
254         if (!WIFEXITED(status))
255                 child_fail(out, outlen, "Killed by signal %u: ",
256                            WTERMSIG(status));
257         /* Child printed failure already, just pass up exit code. */
258         if (type == FAILURE) {
259                 fprintf(stderr, "%.*s", (int)outlen, out);
260                 tell_parent(type);
261                 exit(WEXITSTATUS(status) ? WEXITSTATUS(status) : 1);
262         }
263         if (WEXITSTATUS(status) != 0)
264                 child_fail(out, outlen, "Exited with status %i: ",
265                            WEXITSTATUS(status));
266
267         free(out);
268         signal(SIGUSR1, SIG_DFL);
269
270         /* We continue onwards without failing. */
271         call->fail = false;
272         return false;
273 }
274
275 void *failtest_calloc(size_t nmemb, size_t size,
276                       const char *file, unsigned line)
277 {
278         struct failtest_call *p;
279         struct calloc_call call;
280         call.nmemb = nmemb;
281         call.size = size;
282         p = add_history(FAILTEST_CALLOC, file, line, &call);
283
284         if (should_fail(p)) {
285                 p->u.calloc.ret = NULL;
286                 p->error = ENOMEM;
287         } else {
288                 p->u.calloc.ret = calloc(nmemb, size);
289         }
290         errno = p->error;
291         return p->u.calloc.ret;
292 }
293
294 void *failtest_malloc(size_t size, const char *file, unsigned line)
295 {
296         struct failtest_call *p;
297         struct malloc_call call;
298         call.size = size;
299
300         p = add_history(FAILTEST_MALLOC, file, line, &call);
301         if (should_fail(p)) {
302                 p->u.calloc.ret = NULL;
303                 p->error = ENOMEM;
304         } else {
305                 p->u.calloc.ret = malloc(size);
306         }
307         errno = p->error;
308         return p->u.calloc.ret;
309 }
310
311 void *failtest_realloc(void *ptr, size_t size, const char *file, unsigned line)
312 {
313         struct failtest_call *p;
314         struct realloc_call call;
315         call.size = size;
316         p = add_history(FAILTEST_REALLOC, file, line, &call);
317
318         /* FIXME: Try one child moving allocation, one not. */
319         if (should_fail(p)) {
320                 p->u.realloc.ret = NULL;
321                 p->error = ENOMEM;
322         } else {
323                 p->u.realloc.ret = realloc(ptr, size);
324         }
325         errno = p->error;
326         return p->u.realloc.ret;
327 }
328
329 int failtest_open(const char *pathname, int flags,
330                   const char *file, unsigned line, ...)
331 {
332         struct failtest_call *p;
333         struct open_call call;
334
335         call.pathname = strdup(pathname);
336         call.flags = flags;
337         if (flags & O_CREAT) {
338                 va_list ap;
339                 va_start(ap, line);
340                 call.mode = va_arg(ap, mode_t);
341                 va_end(ap);
342         }
343         p = add_history(FAILTEST_OPEN, file, line, &call);
344         if (should_fail(p)) {
345                 p->u.open.ret = -1;
346                 /* FIXME: Play with error codes? */
347                 p->error = EACCES;
348         } else {
349                 p->u.open.ret = open(pathname, flags, call.mode);
350         }
351         errno = p->error;
352         return p->u.open.ret;
353 }
354
355 int failtest_pipe(int pipefd[2], const char *file, unsigned line)
356 {
357         struct failtest_call *p;
358         struct pipe_call call;
359
360         p = add_history(FAILTEST_PIPE, file, line, &call);
361         if (should_fail(p)) {
362                 p->u.open.ret = -1;
363                 /* FIXME: Play with error codes? */
364                 p->error = EMFILE;
365         } else {
366                 p->u.pipe.ret = pipe(p->u.pipe.fds);
367         }
368         /* This causes valgrind to notice if they use pipefd[] after failure */
369         memcpy(pipefd, p->u.pipe.fds, sizeof(p->u.pipe.fds));
370         errno = p->error;
371         return p->u.pipe.ret;
372 }
373
374 ssize_t failtest_read(int fd, void *buf, size_t count,
375                       const char *file, unsigned line)
376 {
377         struct failtest_call *p;
378         struct read_call call;
379         call.fd = fd;
380         call.buf = buf;
381         call.count = count;
382         p = add_history(FAILTEST_READ, file, line, &call);
383
384         /* This is going to change seek offset, so save it. */
385         if (control_fd != -1)
386                 save_fd_orig(fd);
387
388         /* FIXME: Try partial read returns. */
389         if (should_fail(p)) {
390                 p->u.read.ret = -1;
391                 p->error = EIO;
392         } else {
393                 p->u.read.ret = read(fd, buf, count);
394         }
395         errno = p->error;
396         return p->u.read.ret;
397 }
398
399 static struct write_info *new_write(void)
400 {
401         writes = realloc(writes, (writes_num + 1) * sizeof(*writes));
402         return &writes[writes_num++];
403 }
404
405 ssize_t failtest_write(int fd, const void *buf, size_t count,
406                        const char *file, unsigned line)
407 {
408         struct failtest_call *p;
409         struct write_call call;
410         off_t offset;
411
412         call.fd = fd;
413         call.buf = buf;
414         call.count = count;
415         p = add_history(FAILTEST_WRITE, file, line, &call);
416
417         offset = lseek(fd, 0, SEEK_CUR);
418
419         /* If we're a child, save contents and tell parent about write. */
420         if (control_fd != -1) {
421                 struct write_info *winfo = new_write();
422                 enum info_type type = WRITE;
423
424                 save_fd_orig(fd);
425
426                 winfo->hdr.len = count;
427                 winfo->hdr.fd = fd;
428                 winfo->data = malloc(count);
429                 memcpy(winfo->data, buf, count);
430                 winfo->hdr.offset = offset;
431                 if (winfo->hdr.offset != (off_t)-1) {
432                         lseek(fd, offset, SEEK_SET);
433                         winfo->olddata = malloc(count);
434                         winfo->oldlen = read(fd, winfo->olddata, count);
435                         if (winfo->oldlen == -1)
436                                 winfo->oldlen = 0;
437                 }
438                 write_all(control_fd, &type, sizeof(type));
439                 write_all(control_fd, &winfo->hdr, sizeof(winfo->hdr));
440                 write_all(control_fd, winfo->data, count);
441         }
442
443         /* FIXME: Try partial write returns. */
444         if (should_fail(p)) {
445                 p->u.write.ret = -1;
446                 p->error = EIO;
447         } else {
448                 /* FIXME: We assume same write order in parent and child */
449                 if (child_writes_num != 0) {
450                         if (child_writes[0].hdr.fd != fd)
451                                 errx(1, "Child wrote to fd %u, not %u?",
452                                      child_writes[0].hdr.fd, fd);
453                         if (child_writes[0].hdr.offset != offset)
454                                 errx(1, "Child wrote to offset %zu, not %zu?",
455                                      (size_t)child_writes[0].hdr.offset,
456                                      (size_t)offset);
457                         if (child_writes[0].hdr.len != count)
458                                 errx(1, "Child wrote length %zu, not %zu?",
459                                      child_writes[0].hdr.len, count);
460                         if (memcmp(child_writes[0].data, buf, count)) {
461                                 child_fail(NULL, 0,
462                                            "Child wrote differently to"
463                                            " fd %u than we did!\n", fd);
464                         }
465                         free(child_writes[0].data);
466                         child_writes_num--;
467                         memmove(&child_writes[0], &child_writes[1],
468                                 sizeof(child_writes[0]) * child_writes_num);
469
470                         /* Is this is a socket or pipe, child wrote it
471                            already. */
472                         if (offset == (off_t)-1) {
473                                 p->u.write.ret = count;
474                                 errno = p->error;
475                                 return p->u.write.ret;
476                         }
477                 }
478                 p->u.write.ret = write(fd, buf, count);
479         }
480         errno = p->error;
481         return p->u.write.ret;
482 }
483
484 /* We only trap this so we can dup fds in case we need to restore. */
485 int failtest_close(int fd)
486 {
487         unsigned int i;
488         int newfd = -1;
489
490         for (i = 0; i < fd_orig_num; i++) {
491                 if (fd_orig[i].fd == fd) {
492                         fd_orig[i].fd = newfd = dup(fd);
493                         fd_orig[i].dupped = true;
494                 }
495         }
496
497         for (i = 0; i < writes_num; i++) {
498                 if (writes[i].hdr.fd == fd)
499                         writes[i].hdr.fd = newfd;
500         }
501         return close(fd);
502 }
503
504 void failtest_init(int argc, char *argv[])
505 {
506         if (argc == 2
507             && strncmp(argv[1], "--failpath=", strlen("--failpath=")) == 0) {
508                 failpath = argv[1] + strlen("--failpath=");
509         }
510 }
511
512 void failtest_exit(int status)
513 {
514         unsigned int i;
515
516         if (control_fd == -1)
517                 exit(status);
518
519         if (failtest_exit_check) {
520                 if (!failtest_exit_check(history, history_num))
521                         child_fail(NULL, 0, "failtest_exit_check failed\n");
522         }
523
524         /* Restore any stuff we overwrote. */
525         for (i = 0; i < writes_num; i++) {
526                 if (writes[i].hdr.offset == (off_t)-1)
527                         continue;
528                 if (writes[i].oldlen != 0) {
529                         lseek(writes[i].hdr.fd, writes[i].hdr.offset,
530                               SEEK_SET);
531                         write(writes[i].hdr.fd, writes[i].olddata,
532                               writes[i].oldlen);
533                 }
534         }
535
536         /* Fix up fd offsets, restore sizes. */
537         for (i = 0; i < fd_orig_num; i++) {
538                 lseek(fd_orig[i].fd, fd_orig[i].offset, SEEK_SET);
539                 ftruncate(fd_orig[i].fd, fd_orig[i].size);
540                 /* Free up any file descriptors we dup'ed. */
541                 if (fd_orig[i].dupped)
542                         close(fd_orig[i].fd);
543         }
544
545         tell_parent(SUCCESS);
546         exit(0);
547 }