Why is the x86 undefined instruction called ud2? Why 2?
Article URL: https://devblogs.microsoft.com/oldnewthing/20260910-00/?p=112689 Comments URL: https://news.ycombinator.com/item?id=49683262 Points: 161 # Comments: 39
The x86 undefined instruction, often referred to as ud2, is an architecturally undefined instruction designed to raise an "invalid opcode" exception. This instruction, which is guaranteed to trigger an error, is commonly used by compilers to mark unreachable code. If a function marked with [[noreturn]] returns unexpectedly, the compiler will insert a ud2 instruction, causing the program to crash instead of continuing to the next function.
Initially, there was no architecturally undefined instruction on x86. Developers had to search for a byte sequence that reliably raised the invalid opcode exception when executed. They discovered that the 0F FF sequence led to an invalid opcode exception, although the instruction was internally decoded as if it took two parameters, a register destination and a register-or-memory source. These parameters were never utilized since the invalid opcode exception was raised before any operation could occur.
Meanwhile, another group found that the 0F B9 sequence exhibited similar properties. This discrepancy led to two factions: those who favored the 0F FF sequence and those who adhered to the 0F B9 variant. Eventually, Intel released a new processor that altered the behavior of the 0F FF sequence, causing some programs to malfunction. After extensive investigation, they determined that these programs depended on the 0F FF instruction's behavior as an invalid opcode exception.
Intel responded by officially creating an undefined instruction and naming it ud2 to replace the 0F FF variant. The name ud2 was chosen because the 0F FF variant was retroactively labeled as ud0, and the 0F B9 variant became ud1. With ud2, Intel provided a two-byte instruction without parameters, eliminating the confusion associated with the random decoded parameters of the 0F FF and 0F B9 variants.
While it might seem that ud0 and ud1 could also be considered two-byte invalid opcodes, the presence of unused parameters in these instructions warrants consideration. Although the processor does not use these parameters, decoding an instruction that extends into a non-existent page can result in an access violation rather than an invalid opcode exception. To maintain consistency and architectural guarantee, the ud2 instruction was favored over the other options.
Written by urgent.news from Hacker News Best's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.
This story
This is one outlet's version. Read the fullest account.
- Why is the x86 undefined instruction called ud2? Why 2? devblogs.microsoft.com