Skip to content

Instantly share code, notes, and snippets.

@snickerbockers
Created December 24, 2022 03:39
Show Gist options
  • Save snickerbockers/9849d26203c2dda098c99691bad137e5 to your computer and use it in GitHub Desktop.
Save snickerbockers/9849d26203c2dda098c99691bad137e5 to your computer and use it in GitHub Desktop.
memory backpatch state machine

mem_access

this is an object that tracks a memory access (either read or write) in a code block. There will be one mem_access object for each memory access; thus any given code block could contain several mem_access objects or none at all.

mem_access will contain information that will be needed to backpatch the corresponding memory access; alternatively we might instead recompile the entire code block instead of backpatching (probably less efficient but also less complicated).

states

STATE_NAIVE

this is the initial state of all mem_access objects. STATE_NAIVE means that we implement the memory access by calling memory_map_get_region then calling the corresponding read/write function in that region. The region returned by memory_map_get_region is stored in the mem_access object.

If the region ever changes, then the object transitions to the STATE_VARIABLE state. If the region is always the same after N accesses (where N is a natural number, im thinking maybe 3) then the object will instead transition to STATE_COMMITTED

STATE_COMMITTED

this represents a mem_access object that has only ever been observed accessing a single memory region. As an optimization, the access will be backpatched so that instead of calling memory_map_get_region, it will instead check the address against the bounds of the region that it always accesses and then (if the address was within bounds) it will immediately call the corresponding read/write function.

Should the access ever not lie within the bounds of the expected region, then the object will transition to STATE_VARIABLE state

This state is the most optimized one because only one branch is needed, and the read/write function that gets called will be hardcoded. In the case of writes to RAM we can even just inline the write like the native_mem code used to do.

STATE_VARIABLE

this represents a mem_access object which has been observed accessing more than one memory region; as thus we have very limited options for optimization. the memory access will be backpatched to call memory_map_read_*/memory_map_write_*.

a mem_access object that is in STATE_VARIABLE will never transition to another state.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment