Truly abort on any panic

I am writing code for a custom RISC-V target and I am optimizing for small code size. When any panic happens, I want the code to jump to my custom abort function, no questions asked. I don't want any "unwind" stuff and certainly no pretty format messages.

I've set panic = "abort" in my Cargo.toml. Furthermore, there also is "panic-strategy": "abort" configured for my target. I thought this would do what I described. However, when looking at the generated file, I still see symbols like core::panicking::panic, rust_begin_unwind or core::panicking::panic_fmt. I'd like to have them not exist.

I've seen that there is https://github.com/rust-lang/rust/pull/32900 and the respective RFC and I guess that #![panic_runtime] somehow is what I am looking for. However, I could not find any good instructions on how to use it.

I'm unfortunately not very well informed on current situation with optimization of panic bloatware, but I think you'll have more luck by completely eliminating panics from within your code

You can see for example one way to fail compilation if panic is present
panic-never/lib.rs at master · japaric/panic-never (github.com)

I think this is the only way to guarantee that you avoid panic overhead (it also means you need to compile with optimizations)

I hope this helps, it’s the only resource I have on this.

https://doc.rust-lang.org/stable/reference/runtime.html#the-panic_handler-attribute

I'd suggest taking a look at this and the surrounding sections.

1 Like

@DoumanAsh never panicking isn't really an option here, because (a) I'd like to use it as a quick mechanism for nonrecoverable error handling. Also, there are some slice bounds checks in my code that I'd like to have and they'd be annoying to avoid.

@Rustaceous I am already setting a panic handler that aborts, and as described above, it isn't enough.

@cole-miller Thank you, this hugely cut down my binary size! The usage is a bit clunky though, I should have a look at this Xargo thing and see if it helps.

I understand that, but as I said it is easiest solution.
All these useless checks can be avoided by using unsafe, but that of course rely on you being able to write safe code.
cole-miller's suggestion is good one though, even if you need hassle to set it up, but I would consider eventually getting rid of panics as they are not as helpful as C++'s exceptions to report errors.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.