Why do we need ud2 when int 6 is right there?
The ud2 instruction was created to be an architecturally undefined instruction. However, one might wonder why not simply use an int 6 instruction to achieve the same effect. After all, int 6 is a two-byte instruction, and interrupt vector 6 is designated as the invalid opcode vector, allowing a program to manually invoke it and receive the operating system's assigned behavior for an attempt at executing an invalid opcode.
In theory, the fault generated by this process would report the address of the faulty instruction to the exception handler. The distinction between faults and traps is crucial. Faults represent errors the kernel may attempt to repair and retry, such as page faults or access violations. In contrast, traps report operations that have already occurred, providing an opportunity for special handling before resuming execution.
While some faults might be irreparable, reporting them as faults necessitates additional steps if retrying the instruction is desired. Ignoring a fault would cause the instruction to restart and fault again. Instead of relying on the kernel's handling, manually raising the int 6 interrupt to simulate a #UD (undefined instruction) fault could lead to confusion for the fault handler.
The handler expects the instruction pointer in the fault frame to point to the undefined instruction, but with int 6, it receives the address of the subsequent instruction instead. This discrepancy could leave the handler questioning why the fault was generated in the first place. One scenario where examining the faulting instruction is useful is emulating missing instructions from older processors.
Protected mode further complicates matters, requiring specific CPU privilege levels for issuing int 6. Operating systems typically deny user mode access to this privilege, making it impossible to replicate a #UD fault through an int 6 instruction. To trigger the #UD undefined instruction fault, one must resort to executing an actual undefined instruction.
Raymond, with over 30 years of involvement in Windows, has shared insights through his website The Old New Thing, which has since grown immensely popular.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.