aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 3ae07b9d7060bcdb1c41a2ee1d444c8fb763a110
parent 74bceda813be0ce595880a103245ba0069abcb31
Author: anon <anon@example.com>
Date:   Mon, 19 Oct 2026 21:55:52 +0000

Share lifted Wasm bodies and preserve large guest heap holes

Diffstat:
Msrc/Makefile.wasm | 15++++++++++++++-
Msrc/runtime/guest_heap.c | 36++++++++++++++++++++++++++----------
Msrc/tests/guest_heap.c | 23+++++++++++++++++++++++
Atools/client/share_guest_bodies.py | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_share_guest_bodies.py | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 194 insertions(+), 11 deletions(-)

diff --git a/src/Makefile.wasm b/src/Makefile.wasm @@ -19,10 +19,23 @@ build/wasm/resolved-calls.js: build/portable/tests/resolved_calls.c runtime/gues @mkdir -p $(@D) $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -o $@ -$(patsubst %.c,build/wasm/objects/%.o,$(RESOLVED_CALL_SOURCES)): build/wasm/objects/%.o: build/portable/%.c +$(patsubst %.c,build/wasm/objects/%.o,$(wildcard game/*/*.c)): build/wasm/objects/%.o: build/wasm/shared/%.c @mkdir -p $(@D) $(CC) $(CPPFLAGS) $(CFLAGS) -MMD -MP -c $< -o $@ +# Share equivalent guest entry bodies only in the full Wasm compiler inputs. +build/wasm/shared/%.c: %.c ../tools/client/share_guest_bodies.py + @mkdir -p $(@D) + python3 ../tools/client/share_guest_bodies.py $< $@ + +$(addprefix build/wasm/shared/,$(RESOLVED_CALL_SOURCES)): build/wasm/shared/%.c: build/portable/%.c ../tools/client/share_guest_bodies.py + @mkdir -p $(@D) + python3 ../tools/client/share_guest_bodies.py $< $@ + +build/wasm/guest-heap.js: tests/guest_heap.c runtime/guest_heap.c runtime/guest_memory.c runtime/guest_heap.h runtime/guest_memory.h Makefile.wasm + @mkdir -p $(@D) + $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -o $@ + build/wasm/terrain-occlusion.js: tests/terrain_occlusion.c game/bbr.dll/lifted-0064.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h @mkdir -p $(@D) $(CC) $(CPPFLAGS) $(CFLAGS) -DRECOMP_YIELD_EVERY=16 $(filter %.c,$^) -o $@ diff --git a/src/runtime/guest_heap.c b/src/runtime/guest_heap.c @@ -22,11 +22,17 @@ static SRWLOCK mutex = SRWLOCK_INIT; #else static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; #endif -static struct block *free_blocks; +static struct block *free_blocks[32]; /* One bucket per aligned offset in a 1 MiB arena; collisions retain full addresses. */ static struct block *allocated[65536]; static uint32_t next_address = 0x60000000u; +/* Free ranges of comparable sizes share a bucket. Sizes are always nonzero. */ +static unsigned free_bucket(uint32_t size) +{ + return 31u - __builtin_clz(size); +} + static struct block **allocation_link_locked(uint32_t address) { struct block **link = &allocated[(address >> 4) & 65535]; @@ -41,7 +47,7 @@ static struct block **allocation_link_locked(uint32_t address) static void remove_free_locked(struct block *block) { if (block->free_previous) block->free_previous->free_next = block->free_next; - else free_blocks = block->free_next; + else free_blocks[free_bucket(block->size)] = block->free_next; if (block->free_next) block->free_next->free_previous = block->free_previous; } @@ -49,9 +55,10 @@ static void add_free_locked(struct block *block) { block->free = 1; block->free_previous = NULL; - block->free_next = free_blocks; - if (free_blocks) free_blocks->free_previous = block; - free_blocks = block; + unsigned bucket = free_bucket(block->size); + block->free_next = free_blocks[bucket]; + if (free_blocks[bucket]) free_blocks[bucket]->free_previous = block; + free_blocks[bucket] = block; } static uint32_t guest_malloc_locked(uint32_t size) @@ -60,12 +67,22 @@ static uint32_t guest_malloc_locked(uint32_t size) if (aligned > 0x8fff0000u) return 0; uint32_t needed = (uint32_t)aligned; + /* Preserve large holes by choosing the smallest suitable free range. */ + struct block *block = NULL; + for (unsigned bucket = free_bucket(needed); bucket < 32 && !block; ++bucket) { + for (struct block *candidate = free_blocks[bucket]; candidate; candidate = candidate->free_next) { + if (candidate->size < needed || (block && candidate->size >= block->size)) continue; + block = candidate; + if (block->size == needed) break; + } + } + /* Reuse and split free blocks within one contiguous host allocation. */ - for (struct block *block = free_blocks; block; block = block->free_next) { - if (block->size < needed) continue; + if (block) { if (block->size > needed) { struct block *remainder = calloc(1, sizeof(*remainder)); if (!remainder) return 0; + remove_free_locked(block); remainder->address = block->address + needed; remainder->size = block->size - needed; remainder->previous = block; @@ -74,8 +91,7 @@ static uint32_t guest_malloc_locked(uint32_t size) block->next = remainder; block->size = needed; add_free_locked(remainder); - } - remove_free_locked(block); + } else remove_free_locked(block); block->free = 0; unsigned bucket = (block->address >> 4) & 65535; block->hash_next = allocated[bucket]; @@ -87,7 +103,7 @@ static uint32_t guest_malloc_locked(uint32_t size) uint32_t span = (needed + 0xffffu) & ~0xffffu; if (span < 0x100000u) span = 0x100000u; if (span > 0xefff0000u - next_address) return 0; - struct block *block = calloc(1, sizeof(*block)); + block = calloc(1, sizeof(*block)); if (!block) return 0; if (!guest_map("heap", next_address, span)) { free(block); return 0; } block->address = next_address; diff --git a/src/tests/guest_heap.c b/src/tests/guest_heap.c @@ -93,8 +93,31 @@ static void fragmented_allocation_lifetime(void) guest_free(joined); } +static void small_allocations_preserve_large_holes(void) +{ + uint32_t small = guest_malloc(256); + uint32_t first_guard = guest_malloc(16); + uint32_t large = guest_malloc(4096); + uint32_t second_guard = guest_malloc(16); + uint32_t tail = guest_malloc(0xfeee0); /* Occupy the rest of the 1 MiB arena. */ + guest_free(small); + guest_free(large); + + uint32_t reused_small = guest_malloc(256); + uint32_t reused_large = guest_malloc(4096); + + assert(reused_small == small); + assert(reused_large == large); + guest_free(reused_small); + guest_free(reused_large); + guest_free(first_guard); + guest_free(second_guard); + guest_free(tail); +} + int main(void) { + small_allocations_preserve_large_holes(); realloc_preserves_bytes(); free_coalesces_within_arena(); failed_realloc_preserves_allocation(); diff --git a/tools/client/share_guest_bodies.py b/tools/client/share_guest_bodies.py @@ -0,0 +1,57 @@ +"""Share identical lifted bodies while retaining their guest entry points.""" +import collections +import pathlib +import re +import sys + + +def share_bodies(source): + functions = list(re.finditer(r'^void sub_([0-9A-F]+)\(void\) \{\n', source, re.M)) + if not functions or re.search(r'^\s*#', source[functions[0].end():], re.M): + return source + + # Compare complete bodies, changing only the entry address and entry jump. + groups = collections.defaultdict(list) + for index, function in enumerate(functions): + end = functions[index + 1].start() if index + 1 < len(functions) else len(source) + body = source[function.end():end].rstrip() + if not body.endswith('}') or re.search(r'\b(static|entry_address|__\w+)\b', body): + continue + enter = ' RECOMP_ENTER(0x' + function[1] + 'u);\n' + if body.count(enter) != 1: + continue + before, after = body.split(enter) + jump = re.match(r'\n goto (L_[0-9A-F]+);\n', after) + target = jump[1] if jump else None + if jump: + after = '\n' + after[jump.end():] + groups[before, after].append((function, end, target)) + + # Keep wrappers callable through the original dispatch table and direct calls. + replacements = [] + for (before, after), group in groups.items(): + if len(group) < 2: + continue + name = 'shared_body_' + group[0][0][1] + helper = '\n'.join('void sub_' + function[1] + '(void);' for function, end, target in group) + helper += '\n\n/* Dispatch equivalent guest entry points through one lifted body. */\n' + helper += 'static __attribute__((noinline)) void ' + name + '(uint32_t entry_address) {\n' + helper += before + ' RECOMP_ENTER(entry_address);\n' + helper += ' switch (entry_address) {\n' + for function, end, target in group: + if target: + helper += ' case 0x' + function[1] + 'u: goto ' + target + ';\n' + helper += ' default: break;\n }\n' + after + '\n\n' + for index, (function, end, target) in enumerate(group): + wrapper = 'void sub_' + function[1] + '(void) {\n' + wrapper += ' ' + name + '(0x' + function[1] + 'u);\n}\n\n' + replacements.append((function.start(), end, (helper if index == 0 else '') + wrapper)) + + for start, end, replacement in sorted(replacements, reverse=True): + source = source[:start] + replacement + source[end:] + return source + + +if __name__ == '__main__': + source, output = map(pathlib.Path, sys.argv[1:]) + output.write_text(share_bodies(source.read_text())) diff --git a/tools/client/test_share_guest_bodies.py b/tools/client/test_share_guest_bodies.py @@ -0,0 +1,74 @@ +import pathlib +import subprocess +import tempfile +import unittest + +import share_guest_bodies + + +class SharedBodiesTest(unittest.TestCase): + def test_entry_jumps_fallthrough_and_exception_resume(self): + prefix = '''#include <stdint.h> +#include <setjmp.h> +#include <stdio.h> +#define RECOMP_ENTER(address) current = address +uint32_t current; +int value, throw_now; +jmp_buf resume; +''' + body = ''' RECOMP_ENTER(ADDRESS); + +JUMP value += 100; +L_1000: + value += 3; + if (setjmp(resume)) goto L_3000; + if (throw_now) longjmp(resume, 1); +L_2000: + value += 5; + return; +L_3000: + value += 7; +} + +''' + source = prefix + for address, jump in [('1000', ''), ('2000', ' goto L_2000;\n'), ('3000', ' goto L_3000;\n')]: + source += 'void sub_' + address + '(void) {\n' + source += body.replace('ADDRESS', '0x' + address + 'u').replace('JUMP', jump) + source += '''int main(void) { + sub_1000(); printf("%u %d\\n", current, value); + value = 0; sub_2000(); printf("%u %d\\n", current, value); + value = 0; sub_3000(); printf("%u %d\\n", current, value); + value = 0; throw_now = 1; sub_1000(); printf("%u %d\\n", current, value); + return 0; +} +''' + # Keep the test driver separate from the strict generated function input. + driver = source[source.index('int main(void)'):] + generated = source[:source.index('int main(void)')] + + transformed = share_guest_bodies.share_bodies(generated) + results = [] + with tempfile.TemporaryDirectory() as temporary: + path = pathlib.Path(temporary) + for name, program in [('original', generated), ('shared', transformed)]: + (path / (name + '.c')).write_text(program + driver) + subprocess.run(['gcc', '-O2', str(path / (name + '.c')), '-o', str(path / name)], check=True) + results.append(subprocess.check_output([str(path / name)], text=True)) + + self.assertEqual(transformed.count('static __attribute__((noinline))'), 1) + self.assertEqual(results, ['4096 108\n8192 5\n12288 7\n4096 110\n'] * 2) + + def test_per_function_storage_is_preserved(self): + source = '#include <stdint.h>\n' + for address in ['1000', '2000']: + source += 'void sub_' + address + '(void) {\n' + source += ' static int counter;\n RECOMP_ENTER(0x' + address + 'u);\n counter++;\n}\n\n' + + transformed = share_guest_bodies.share_bodies(source) + + self.assertEqual(transformed, source) + + +if __name__ == '__main__': + unittest.main()