+struct saved_file {
+ struct saved_file *next;
+ int fd;
+ void *contents;
+ off_t off, len;
+};
+
+static struct saved_file *save_file(struct saved_file *next, int fd)
+{
+ struct saved_file *s = malloc(sizeof(*s));
+
+ s->next = next;
+ s->fd = fd;
+ s->off = lseek(fd, 0, SEEK_CUR);
+ /* Special file? Erk... */
+ assert(s->off != -1);
+ s->len = lseek(fd, 0, SEEK_END);
+ lseek(fd, 0, SEEK_SET);
+ s->contents = malloc(s->len);
+ read(fd, s->contents, s->len);
+ lseek(fd, s->off, SEEK_SET);
+ return s;
+}
+
+/* We have little choice but to save and restore open files: mmap means we
+ * can really intercept changes in the child.
+ *
+ * We could do non-mmap'ed files on demand, however. */
+static struct saved_file *save_files(void)
+{
+ struct saved_file *files = NULL;
+ int i;
+
+ /* Figure out the set of live fds. */
+ for (i = history_num - 2; i >= 0; i--) {
+ if (history[i].type == FAILTEST_OPEN) {
+ int fd = history[i].u.open.ret;
+ /* Only do successful, writable fds. */
+ if (fd < 0)
+ continue;
+
+ /* If it was closed, cleanup == NULL. */
+ if (!history[i].cleanup)
+ continue;
+
+ if ((history[i].u.open.flags & O_RDWR) == O_RDWR) {
+ files = save_file(files, fd);
+ } else if ((history[i].u.open.flags & O_WRONLY)
+ == O_WRONLY) {
+ /* FIXME: Handle O_WRONLY. Open with O_RDWR? */
+ abort();
+ }
+ }
+ }
+
+ return files;
+}
+
+static void restore_files(struct saved_file *s)
+{
+ while (s) {
+ struct saved_file *next = s->next;
+
+ lseek(s->fd, 0, SEEK_SET);
+ write(s->fd, s->contents, s->len);
+ ftruncate(s->fd, s->len);
+ free(s->contents);
+ lseek(s->fd, s->off, SEEK_SET);
+ free(s);
+ s = next;
+ }
+}
+
+/* Free up memory, so valgrind doesn't report leaks. */
+static void free_everything(void)
+{
+ unsigned int i;
+
+ /* We don't do this in cleanup: needed even for failed opens. */
+ for (i = 0; i < history_num; i++) {
+ if (history[i].type == FAILTEST_OPEN)
+ free((char *)history[i].u.open.pathname);
+ }
+ free(history);
+}
+
+static NORETURN void failtest_cleanup(bool forced_cleanup, int status)
+{
+ int i;
+
+ /* For children, we don't care if they "failed" the testing. */
+ if (control_fd != -1)
+ status = 0;
+
+ if (forced_cleanup)
+ history_num--;
+
+ /* Cleanup everything, in reverse order. */
+ for (i = history_num - 1; i >= 0; i--) {
+ if (!history[i].cleanup)
+ continue;
+ if (!forced_cleanup) {
+ printf("Leak at %s:%u\n",
+ history[i].file, history[i].line);
+ status = 1;
+ }
+ history[i].cleanup(&history[i].u);
+ }
+
+ free_everything();
+ tell_parent(SUCCESS);
+ exit(status);
+}
+