How processor handles case of division by zero

Alfred picture Alfred · May 27, 2014 · Viewed 12k times · Source

Curious what the processor/CPU does in general or let say, on intel cpu & Linux, when it executes a division by zero instruction. Also how the error is relayed to the application, so that it can log the error or notify the developer?

Thank you!

Answer

Rob11311 picture Rob11311 · May 27, 2014

To answer in general terms, rather than going into gory details for Linux on x86_64, which are likely to obscure the concepts.

CPUs tend to throw an exception interrupt, on things like division by zero, or dereferencing a NULL pointer. These interrupts are trapped, like when hardware interrupts, halting execution of current program and return control to the OS, which then handles the event. Whilst the actions are very environment dependant, commonly the program may be terminated, all resources freed (memory, open files) and optionally core dumps/stack traces generated for debugging purposes on a developers system.

A runtime might be able to configure things so an exception handler is called, perhaps a scripting language wants to catch integer division by 0, or integer overflow and then throw a programming language exception or generate diagnostics to help the programmer understand where & why, it happened. Raising a signal, which may be caught by the application and handled, or lead to termination, is another traditional possibility.

On some RISC CPUs, software traps in OS would run to fix up misaligned data accesses, so reading memory would work, but with a performance penalty. In past, traps would sometimes be used to emulate, defined instructions but which were not implemented in hardware by a particular CPU model. I've also seen hardware memory errors logged, as OS initiates an ECC memory recovery operation, though that is handled differently on x86.

System calls, actually use the same mechanism to jump, from a user space application, into the OS kernel which then handles the event, hence the common term trap.