+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);
+ 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)