+static void hand_down(int signum)
+{
+ kill(child, signum);
+}
+
+static void release_locks(void)
+{
+ /* Locks were never acquired/reacquired? */
+ if (lock_owner == 0)
+ return;
+
+ /* We own them? Release them all. */
+ if (lock_owner == getpid()) {
+ unsigned int i;
+ struct flock fl;
+ fl.l_type = F_UNLCK;
+ fl.l_whence = SEEK_SET;
+ fl.l_start = 0;
+ fl.l_len = 0;
+
+ for (i = 0; i < lock_num; i++)
+ fcntl(locks[i].fd, F_SETLK, &fl);
+ } else {
+ /* Our parent must have them; pass request up. */
+ enum info_type type = RELEASE_LOCKS;
+ assert(control_fd != -1);
+ write_all(control_fd, &type, sizeof(type));
+ }
+ lock_owner = 0;
+}
+
+/* off_t is a signed type. Getting its max is non-trivial. */
+static off_t off_max(void)
+{
+ BUILD_ASSERT(sizeof(off_t) == 4 || sizeof(off_t) == 8);
+ if (sizeof(off_t) == 4)
+ return (off_t)0x7FFFFFF;
+ else
+ return (off_t)0x7FFFFFFFFFFFFFFULL;
+}
+
+static void get_locks(void)
+{
+ unsigned int i;
+ struct flock fl;
+
+ if (lock_owner == getpid())
+ return;
+
+ if (lock_owner != 0) {
+ enum info_type type = RELEASE_LOCKS;
+ assert(control_fd != -1);
+ write_all(control_fd, &type, sizeof(type));
+ }
+
+ fl.l_whence = SEEK_SET;
+
+ for (i = 0; i < lock_num; i++) {
+ fl.l_type = locks[i].type;
+ fl.l_start = locks[i].start;
+ if (locks[i].end == off_max())
+ fl.l_len = 0;
+ else
+ fl.l_len = locks[i].end - locks[i].start + 1;
+
+ if (fcntl(locks[i].fd, F_SETLKW, &fl) != 0)
+ abort();
+ }
+ lock_owner = getpid();
+}
+
+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);
+ 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();
+ }
+ }
+ }
+
+ return files;
+}
+
+static void restore_files(struct saved_file *s)