+/* A huge hack: to make up for the wastefulness of shared libraries
+ * needing at least a page of dirty memory even if they have no global
+ * data, we reclaim the gaps at the beginning and end of writable maps
+ * and "donate" them to the heap by setting up minimal malloc
+ * structures and then freeing them. */
+
+static void reclaim(unsigned char *base, size_t start, size_t end)
+{
+ size_t *a, *z;
+ start = start + 6*sizeof(size_t)-1 & -4*sizeof(size_t);
+ end = (end & -4*sizeof(size_t)) - 2*sizeof(size_t);
+ if (start>end || end-start < 4*sizeof(size_t)) return;
+ a = (size_t *)(base + start);
+ z = (size_t *)(base + end);
+ a[-2] = 1;
+ a[-1] = z[0] = end-start + 2*sizeof(size_t) | 1;
+ z[1] = 1;
+ free(a);
+}
+
+static void reclaim_gaps(unsigned char *base, Phdr *ph, size_t phent, size_t phcnt)
+{
+ for (; phcnt--; ph=(void *)((char *)ph+phent)) {
+ if (ph->p_type!=PT_LOAD) continue;
+ if ((ph->p_flags&(PF_R|PF_W))!=(PF_R|PF_W)) continue;
+ reclaim(base, ph->p_vaddr & -PAGE_SIZE, ph->p_vaddr);
+ reclaim(base, ph->p_vaddr+ph->p_memsz,
+ ph->p_vaddr+ph->p_memsz+PAGE_SIZE-1 & -PAGE_SIZE);
+ }
+}
+