What are temporal and spatial memory safety?
— 2024-12-15
The lovely folks working on security over at Google have recently been writing about "temporal (memory) safety" and "spatial (memory) safety". When I first saw these terms it took me a minute to figure out what they meant, as searching for it online didn't yield immediate answers. So I figured it might be helpful to write it down for others to find:
- Spatial memory safety: describes violations like out-of-bounds access. Say you have a vec of 10 items, it's undefined behavior if you try and read from the memory location of the non-existent 11th item. You can think of these as violations that have to do with memory regions (space).
- Temporal memory safety: describes violations like use-after-free. Say you have a type that has been de-initialized already ("dropped" in Rust), it's undefined behavior to then try and read from any of its fields. You can think of these as violations that have to do with the ordering of memory operations (time).
My only qualm with these terms is that I've occasionally seen people drop the "memory" qualifier. I think this is part of what makes these terms confusing: there are other many more safety properties 1 involving layout or ordering that can be modeled that don't have anything to do with memory safety. Skimming the entries on Temporal Logic or TLA+ should make that clear enough 2.
When modeling, the term "safety" refers to the absence of a defined negative property. That's in contrast to "liveness" which refers to the presence of a defined positive property. Read more.
If you prefer a concrete example: imagine two concurrent writers to the same TCP socket speaking HTTP. Without careful coordination between the two this will lead to issues involving ordering of operations (temporal safety) that may lead to data loss, data corruption, and so on - but without ever involving involving any memory safety violations.
My ask then is that when discussing spatial memory safety and temporal memory safety to refer to them as such in full. Don't try and shorten them by dropping the "memory" qualifier. Because when discussing formally modeled properties it certainly pays to be specific about what it is that you're trying to guarantee.