In Win32, there is an API call called “MulDiv”:
The MulDiv function multiplies two 32-bit values and then divides the 64-bit result by a third 32-bit value. The return value is rounded up or down to the nearest integer.
int WINAPI MulDiv(
If a divide overflow (including divide by zero) occurs, MulDiv returns -1. (Stupidly, there’s no way to actually check whether the result truly is -1 instead of an error.)
How do we implement this in x86-32? The official version does not use structured exception handling to simply catch the exception and handle it. MulDiv actually checks for overflow beforehand and never causes an exception.
The official implementation is several pages long, and I think we could do much better.
If this were the unsigned case, the entire function would be simple:
mov eax, [esp+4]
mul dword ptr [esp+8]
cmp edx, [esp+12]
div dword ptr [esp+12]
or eax, -1