logoalt Hacker News

yunnpptoday at 3:19 AM1 replyview on HN

> One concern was that Arenas introduced “Use-After-Free” bugs, a classic C++ problem where you access memory after the arena has been cleared, causing a crash.

In Rust, can the lifetime of objects be tied to that of the arena to prevent this?

Asking as a C/C++ programmer with not much Rust experience.


Replies

LegionMammal978today at 3:36 AM

Yes, or rather, the lifetime of references to the contained objects can be tied to the lifetime of references to the arena. E.g., the bumpalo crate [0] has two relevant methods, Bump::alloc(), which puts a value into the arena and gives you back a reference, and Bump::reset(), which erases everything from the arena.

But Bump::reset() takes a &mut self, while Bump::alloc() takes a &self reference and gives back a &mut T reference of the same lifetime. In Rust, &mut references are exclusive, so creating one for Bump::reset() ends the lifetime of all the old &self references, and thus all the old &mut T references you obtained from Bump::alloc(). Ergo, once you call Bump::reset(), none of the contained objects are accessible anymore. The blogpost at [2] gives a few other crates with this same &self -> &mut T pattern.

Meanwhile, some crates such as slab [1] effectively give you a numeric key or token to access objects, and crates differ in whether they have protections to guarantee that keys are unique even if objects are removed. All UAF protection must occur at runtime.

[0] https://docs.rs/bumpalo/3.19.0/bumpalo/struct.Bump.html

[1] https://docs.rs/slab/0.4.11/slab/struct.Slab.html

[2] https://donsz.nl/blog/arenas/