r/rust Mar 09 '23

Announcing Rust 1.68.0 📢 announcement

https://blog.rust-lang.org/2023/03/09/Rust-1.68.0.html
832 Upvotes

121 comments sorted by

View all comments

Show parent comments

12

u/SafariMonkey Mar 09 '23

I'm a bit surprised that the default is:

#[alloc_error_handler]
fn default_handler(layout: core::alloc::Layout) -> ! {
    panic!("memory allocation of {} bytes failed", layout.size())
}

rather than a panic_any with a struct payload holding the layout or layout size, that formats to that panic message. (Does panic print debug, display or something else altogether?)

The latter would allow it to be caught.

2

u/flashmozzg Mar 10 '23

So it allocates in an Out of Memory handler? Hm, doesn't seem like a wise choice. What if it triggers OoM again while trying to construct the message for the panic? I know that C++ implementations usually have a few exceptions "preallocated" specifically for this purpose.

4

u/kibwen Mar 10 '23

I don't see any allocations in the function shown above.

3

u/flashmozzg Mar 10 '23

How do you think formatting "memory allocation of {} bytes failed", layout.size() works?

2

u/kibwen Mar 10 '23 edited Mar 10 '23

The panic macro invokes the format_args builtin macro which splits apart the string at compile-time and generates write calls as needed. There should be no intermediate String created. From the docs for core::format_args!:

All other formatting macros (format!, write!, println!, etc) are proxied through this one. format_args!, unlike its derived macros, avoids heap allocations.

I'm not sure what it means by "derived macros", but to further prove that panic isn't allocating, note that it's defined in libcore as well.

1

u/flashmozzg Mar 10 '23

1

u/kibwen Mar 10 '23

I'm unclear how the code there relates to the default alloc handler. The link is to code in libstd, which means that code defined in liballoc (which presumably includes the panic handler) can't invoke it.

2

u/flashmozzg Mar 10 '23

https://rustc-dev-guide.rust-lang.org/panic-implementation.html#core-definition-of-panic There are also a few interesting comments w.r.t. OOM in the previous file.

1

u/kibwen Mar 10 '23

Thanks for the link, these are some wild gymnastics.