+ 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);
+ if (read(fd, s->contents, s->len) != s->len)
+ err(1, "Failed to save %zu bytes", (size_t)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();
+ }
+ }
+ }