Technology1 min read

Code Smells of Desperation (2023)

By · Published by Everything Blog

In short

The floating-point support library included with Windows 3.0 through 3.11 features an IRQ 13 handler packed with bizarre, redundant instructions that diverge from standard practices. To clear exceptions and stabilize execution, the routine disables interrupts, executes FNCLEX multiple times, and repeatedly writes zero to I/O port F0h. These extreme measures were discovered during WineVDM development to reproduce the specific stack layout needed by Visual Basic. Traced back to early Microsoft C compilers, the code likely reflects frantic engineering to accommodate broken hardware configurations.

Key points

  • Microsoft developers repeatedly patched Windows math emulation to keep invalid exceptions…: Microsoft developers repeatedly patched Windows math emulation to keep invalid exceptions enabled for tracking stack errors.
  • The unusual workarounds and redundant instructions likely served to maintain compatibilit…: The unusual workarounds and redundant instructions likely served to maintain compatibility with buggy historical Intel FPU hardware.
  • Modern WineVDM development uncovered these legacy quirks while trying to satisfy the spec…: Modern WineVDM development uncovered these legacy quirks while trying to satisfy the specific stack layout demands of Visual Basic.

Sources checked by our analysis pipeline: 1

A few weeks ago I had the questionable pleasure of diving into the math exception handler of WIN87EM.DLL, the Windows 3.1 math emulator and FPU support library. Actually WIN87EM.DLL appears to have been first shipped with Windows 3.0, and the version in Windows 3.1 is more or less identical. The version shipped with Windows 3.11 is byte for byte identical to the one in Windows 3.1.

The main function of WIN87EM.DLL is, as the name suggests, an x87 floating-point emulator. It appears to be an outgrowth of the math emulation packages shipped with many Microsoft languages. But even on a system with x87 hardware, WIN87EM.DLL has some work to do.

Namely WIN87EM.DLL intercepts math errors (exceptions). Depending on the system type, WIN87EM.DLL hooks either NMI vector 2 (PC and PC/XT) or IRQ 13 (PC/AT and compatibles).

The math interrupt handler in WIN87EM.DLL is very, very strange. It bears all the hallmarks of code that was written, rewritten, rewritten again, hacked, tweaked, modified, and eventually beaten into submission even if the author(s) had no real idea why it finally worked.

Now,…

Technology