w6l+selfhost: BSS optimisation — trim trailing .data zeros from filesz

Scan the consolidated .data buffer (post-relocation) for trailing zero
bytes; set the R+W PT_LOAD's p_filesz to exclude them while p_memsz
covers the full region. The loader zero-fills the gap, so behaviour is
unchanged. Saves up to a page per binary on programs whose globals are
zero-init.

Mirrored in selfhost/cmd/w6l/out.ww so test 992's byte-identity diff
still holds. Dynamic-link path is untouched — it still errors on any
mutable global; that's the next feature.
This commit is contained in:
2026-05-12 13:44:27 +09:00
parent 548547a1d0
commit 2480f4c272
4 changed files with 142 additions and 16 deletions

View File

@@ -63,11 +63,24 @@ l_emit_elf(Lnk *l, FILE *f, u64 base, u64 entry)
const u64 rx_end = text_off + l->textlen;
const int has_data = (l->datalen > 0);
/* BSS optimisation: trailing zero bytes in .data can be left out
* of the file. The loader zero-fills the gap between p_filesz and
* p_memsz, so this shrinks the binary without changing semantics.
* Scan after l_relocate has applied DATAR patches — anything still
* zero at the tail genuinely is zero-init. */
u64 bsslen = 0;
if (has_data) {
while (bsslen < l->datalen
&& l->data[l->datalen - 1 - bsslen] == 0)
bsslen++;
}
const u64 data_file_len = l->datalen - bsslen;
/* data goes at the next page boundary so the loader can grant a
* fresh page of R+W permissions without overlapping the R+X mapping. */
const u64 data_off = has_data ? ((rx_end + page - 1) & ~(page - 1)) : 0;
const u64 data_va = has_data ? (base + data_off) : 0;
const u64 file_end = has_data ? (data_off + l->datalen) : rx_end;
const u64 file_end = has_data ? (data_off + data_file_len) : rx_end;
(void)data_va;
Ehdr eh = {0};
@@ -104,7 +117,7 @@ l_emit_elf(Lnk *l, FILE *f, u64 base, u64 entry)
phw.p_offset = data_off;
phw.p_vaddr = base + data_off;
phw.p_paddr = base + data_off;
phw.p_filesz = l->datalen;
phw.p_filesz = data_file_len;
phw.p_memsz = l->datalen;
phw.p_align = page;
}
@@ -119,11 +132,11 @@ l_emit_elf(Lnk *l, FILE *f, u64 base, u64 entry)
if (l->textlen) fwrite(l->text, 1, l->textlen, f);
if (has_data) {
if (has_data && data_file_len > 0) {
/* pad to data_off */
here = ftell(f);
for (long i = here; i < (long)data_off; i++) fputc(0, f);
fwrite(l->data, 1, l->datalen, f);
fwrite(l->data, 1, data_file_len, f);
}
(void)file_end;