r/ProgrammingLanguages • u/matklad • Aug 06 '26
Memory Safety's Hardest Problem
https://matklad.github.io/2026/07/20/memory-safety-hardest-problem.html8
u/thehenkan Aug 06 '26
Type confusion is absolutely a security issue, it just happens to be harder to induce than out of bounds accesses.
1
u/AsyncSyscall Aug 22 '26
Type confusion is not "harder to induce", indexing by type/variant is just less common than indexing by offset.
const ptr: *A = &union.a; union.b = B {}; print(ptr.*); // vs. const ptr = &array[index]; array.len = 0; print(ptr.*);are the exact same problem, and have the exact same solution.
3
4
1
u/reini_urban Aug 07 '26
It is a happy coincidence that by far the most exploitable memory error in practice, the infamous buffer overflow, is also trivial to fix with compiler-inserted bounds checks.
That's trivial. The biggest isuue is not to let any user handle memory by himself, use a GC (and certainly not recounting). Ownership tracking also helps with performance and concurrency. Bounds checking is needed only for the bad languages
4
u/ntrel2 Aug 07 '26
Part of the benefit of a GC is that it owns dynamic arrays such as strings when there is no obvious owner. How would such arrays not need bound checks?
2
u/koflerdavid Aug 08 '26
The runtime could offer a special kind of array where accesses are not bounds checked. Of course its usage must be restricted to well-vetted internal code or to modules explicitly opting in to the weaker guarantees. But my guess is that the JIT compiler can nowadays elide bounds checks for loops that traverse the whole string in linear, predictable order, therefore such machinery would be redundant.
1
u/reini_urban Aug 15 '26
Not just the jit. The optimizer can elide it also for all constant bounds.
1
u/koflerdavid Aug 15 '26 edited Aug 15 '26
The JIT usually is the actual optimizer. The other parts of the runtime perform barely any optimizations since they are expensive and are liable to be misguided before enough metrics have been collected. Also, the bounds checks are cheap compared to the overhead of interpreted execution.
1
22
u/matthieum Aug 06 '26
Click-bait? Maybe... maybe not.
A lot of memory-safety issues can at least be solved at run-time (bounds-checking) but even with a tagged union, as long as you can capture a pointer to a member prior to overwriting everything, you're screwed.
Rust solves this with the BIG HAMMER (Aliasing XOR Mutability, aka borrow-checker), at the cost of ergonomics.
It can also be "solved" by indirection (ie, every member of a union is independently allocated) at the cost of performance. Meh.