Why does rustc emit trap instruction for thumbv7m-none-eabi target?

Hi, rustaceans.

It may be a noob question, but I'm writing bare metal rust code for STM32 (thumbv7m-none-eabi) without japaric's HAL in order to make up with how things work.

So, I was researching resulting binaries with radare2 when noticed trap instructions (THUMB opcode 0xDEFE) all over my binary. Why do rustc emit them even if with panic = "abort", -C force-unwind-tables=no and release profile with debug symbols off?

I've noticed this trap instructions turn up only after calls to panic functions, so it seems to be done for debug purposes. Is there any way to prevent such rustc's behaviour or it is hardcoded somewhere?

When you set panic="abort" it means if you ever trigger a panic it'll be converted to some sort of crash/abort the current program. One way to reliably crash is to execute a known illegal instruction.

The program needs to do something when it reaches a panic condition (even if that is just "blow up") so there is no way to remove the traps.

1 Like

Well, then why do I need 4 of them in the whole binary even after calling functions that are not going to fail, such as core::panicking::panic_fmt? Why the presence of #[panic_handler]-marked divergent function is not enough then?

Also, even if I use panic = "unwind" strategy, it doesn't stop rustc from emitting traps...

It's still possible to return from a diverging function even if it is marked as diverging by the type system. For example, what if I used inline assembly to load the return location and jump to it?

I suspect what you are seeing is the compiler taking a "belts and braces" approach. So it inserts an abort() call to make doubly sure that we crash the system instead of going on to execute random instructions.

There is nothing stopping code in the standard library or one of your dependencies from calling core::intrinsics::abort() directly.

1 Like

Sounds like you might be interested in these:


This can be disabled with RUSTFLAGS -Z trap-unreachable=no.


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.