mulreturns 128 bits across two registers, whiledivexpects a 128-bit dividend—one stalerdxis enough to raiseSIGFPE.
In C99, multiplying two uint64_t values silently truncates to 64 bits, and dividing by zero is undefined behavior. At the hardware level, the CPU uses a dedicated register pair and raises a dedicated exception. In this lesson, I cover the RDX:RAX pair, the cqo instruction, and the #DE exception.
Mental Model: A Result Wider Than One Register
| What it looks like in C99 | What happens in hardware |
|---|---|
a * b yields one 64-bit result |
mul writes 128 bits: high half in rdx, low half in rax |
SIGFPE only happens with float |
Integer div and idiv raise #DE |
| The dividend is a single register | The dividend is always the rdx:rax pair |
| Sign extension is automatic | cqo must populate rdx before idiv |
INT64_MIN / -1 is normal division |
The quotient overflows 64 signed bits, so the CPU raises #DE |
mul: A Product in Two Halves
mul multiplies rax by its operand and writes the full 128-bit product into rdx:rax: the low 64 bits land in rax, and the high 64 bits land in rdx.
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; mul128.asm — 128-bit multiplication and division via the RDX:RAX pair.
default rel
section .text
global asm_mul_u64
global asm_divmod_u64
global asm_div_signed
; ------------------------------------------------------------------------------
; uint64_t asm_mul_u64(uint64_t a, uint64_t b, uint64_t *hi)
; Input: rdi = a, rsi = b, rdx = hi
; Output: rax = low 64 bits, *hi = high 64 bits
; Clobbers: rax, rdx, r8, flags (caller-saved)
; ------------------------------------------------------------------------------
asm_mul_u64:
mov rax, rdi
mov r8, rdx
mul rsi
mov [r8], rdx
ret
; ------------------------------------------------------------------------------
; uint64_t asm_divmod_u64(uint64_t hi, uint64_t lo, uint64_t d, uint64_t *rem)
; Input: rdi = hi, rsi = lo, rdx = d, rcx = rem
; Output: rax = quotient, *rem = remainder
; Clobbers: rax, rdx, r8, r9, flags (caller-saved)
; Trap: hi >= d raises #DE (quotient does not fit in 64 bits)
; ------------------------------------------------------------------------------
asm_divmod_u64:
mov rax, rsi
mov r8, rdx
mov r9, rcx
mov rdx, rdi
div r8
mov [r9], rdx
ret
; ------------------------------------------------------------------------------
; int64_t asm_div_signed(int64_t a, int64_t b)
; Input: rdi = a, rsi = b
; Output: rax = quotient rounded toward zero
; Clobbers: rax, rdx, flags (caller-saved)
; Trap: b = 0 and INT64_MIN / -1 raise #DE
; ------------------------------------------------------------------------------
asm_div_signed:
mov rax, rdi
cqo
idiv rsi
ret
section .note.GNU-stack noalloc noexec nowrite progbitsIn asm_mul_u64, the pointer hi arrives in rdx, which mul overwrites. So the pointer moves to r8 first before multiplying.
0000000000000000 <asm_mul_u64>:
0: 48 89 f8 mov rax,rdi
3: 49 89 d0 mov r8,rdx
6: 48 f7 e6 mul rsi
9: 49 89 10 mov QWORD PTR [r8],rdx
c: c3 retmov rax, rdisets up the first factor, becausemulalways readsrax.mov r8, rdxsaves thehipointer beforemulclobbersrdx.mul rsimultipliesraxbyrsiand writes all 128 bits intordx:rax.mov QWORD PTR [r8], rdxstores the high half throughr8.
Testing the boundary case UINT64_MAX * 2 in GDB (using nexti 3 to step three instructions, lesson 05) shows both halves:
Breakpoint 1, asm_mul_u64 () at mul128.asm:19
19 mov rax, rdi
(gdb) nexti 3
22 mov [r8], rdx
(gdb) print/x $rdx
$1 = 0x1
(gdb) print/x $rax
$2 = 0xfffffffffffffffe is 2^65 - 2, the full product (2^64 - 1) * 2. Keeping only rax would silently drop the leading 1.
div: A Dividend Across Two Registers
div divides rdx:rax by its operand. The quotient goes into rax, and the remainder goes into rdx. There is one strict constraint: the quotient must fit in 64 bits, or the CPU raises #DE before writing any result.
000000000000000d <asm_divmod_u64>:
d: 48 89 f0 mov rax,rsi
10: 49 89 d0 mov r8,rdx
13: 49 89 c9 mov r9,rcx
16: 48 89 fa mov rdx,rdi
19: 49 f7 f0 div r8
1c: 49 89 11 mov QWORD PTR [r9],rdx
1f: c3 retmov rax, rsiloads the low half of the dividend intorax.mov rdx, rdiloads the high half intordx; without this,divwould divide garbage inrdx.div r8dividesrdx:raxby the divisor and leaves the remainder inrdx.mov [r9], rdxwrites the remainder throughr9.
The div64.c testbed calls asm_divmod_u64 to divide 2^64 by 10, yielding quotient 1844674407370955161 and remainder 6. Even though the dividend (hi = 1) exceeds 64 bits as a pair, the quotient still fits inside 64 bits.
idiv and cqo: Extending the Sign Across the Pair
Signed division reads the same pair, except rdx must hold the sign extension of rax. That is precisely what cqo does: it replicates bit 63 of rax across every bit of rdx.
0000000000000020 <asm_div_signed>:
20: 48 89 f8 mov rax,rdi
23: 48 99 cqo
25: 48 f7 fe idiv rsi
28: c3 ret48 99 is cqo. Without it, rdx keeps stale bits, causing idiv to raise #DE or return the wrong quotient. Like C99’s /, idiv truncates toward zero: -7 / 2 yields -3.
mul op: rax × op ──► [ rdx (hi 64) | rax (lo 64) ]
div op: [ rdx=0 | rax ] ÷ op ──► rax (quotient), rdx (remainder)
cqo + idiv op: bit 63 of rax ──► all bits of rdx (0x0000... or 0xFFFF...)
[ rdx | rax ] ÷ op ──► rax (quotient), rdx (remainder)#DE Without Floating Point
A common misconception is: “SIGFPE stands for Floating Point Exception, so it only fires on floating-point numbers.” The name is purely historical: exception vector 0 handles integer div and idiv, and Linux maps it to SIGFPE.
The divbug.asm testbed can crash in two ways and succeed in a third:
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; divbug.asm — three division modes: stale rdx and INT64_MIN / -1 raise #DE,
; while the valid call exits with 14.
default rel
%define SYS_EXIT 60
section .text
global _start
; ------------------------------------------------------------------------------
; _start — mode chosen by first byte of argv[1]: "min", "ok", or stale rdx.
; Input: rsp -> argc, argv, NULL, envp, NULL
; Output: does not return; exits with 14 for ok, otherwise dies on #DE
; Clobbers: rax, rcx, rdx, rsi, rdi, r11, flags
; ------------------------------------------------------------------------------
_start:
cmp qword [rsp], 2
jl .dirty
mov rsi, [rsp + 16]
cmp byte [rsi], 'm'
je .min
cmp byte [rsi], 'o'
je .ok
.dirty:
mov rax, 0
mov rdx, 2
mov rcx, 2
div rcx
jmp .exit_ok
.min:
mov rax, 0x8000000000000000
cqo
mov rcx, -1
idiv rcx
jmp .exit_ok
.ok:
mov rax, 100
cqo
mov rcx, 7
idiv rcx
.exit_ok:
; syscall: exit(quotient)
mov edi, eax
mov eax, SYS_EXIT
syscall
section .note.GNU-stack noalloc noexec nowrite progbitsdirtymode setsrdx = 2and divides by 2:(2 * 2^64) / 2doesn’t fit in 64 bits, sodivraises#DE.minmode dividesINT64_MINby-1: the quotient2^63overflows signed 64 bits.okmode runsidivwith valid operands and exits with14.
Exit codes tell the outcomes apart:
$ ./build/divbug ok; echo $?
14
$ ./build/divbug dirty; echo $?
136
$ ./build/divbug min; echo $?
136136 is 128 + 8, termination by SIGFPE; the kernel terminates the process before it can return from #DE. GDB captures the register state at the fault:
Program received signal SIGFPE, Arithmetic exception.
_start.dirty () at divbug.asm:33
33 div rcx
(gdb) print/d $rdx
$1 = 2
(gdb) print/d $rax
$2 = 0
(gdb) print/d $rcx
$3 = 2
(gdb) x/i $rip
=> 0x401025 <_start.dirty+15>: div rcx$1— stale2inrdx; dividing by 2 requiresrdx = 0.$2—rax = 0, the low half of the dividend, harmless on its own.$3— divisor inrcx.div rcx— the faulting instruction;ripstill points to it because#DEis a fault raised before retirement.
In min mode, the register values differ, yet the exception is identical:
Program received signal SIGFPE, Arithmetic exception.
_start.min () at divbug.asm:40
40 idiv rcx
(gdb) print/d $rdx
$1 = -1
(gdb) print/d $rax
$2 = -9223372036854775808
(gdb) print/d $rcx
$3 = -1
(gdb) x/i $rip
=> 0x40103d <_start.min+19>: idiv rcx$1—rdx = -1:cqoextendedrax’s sign across the whole pair.$2—rax, the minimum signed 64-bit integer.$3— divisor-1.
The quotient 2^63 doesn’t fit in a signed 64-bit register, so idiv raises #DE before writing rax.
Common Pitfalls
-
"
divcrashes on an ordinary number."
Fact: withrdx = 2andrcx = 2,div rcxterminates the process with exit code136.
Cause:divreads the dividend fromrdx:rax, notraxalone; a non-zerordxmakes the dividend huge.
Fix: clearrdxwithxor edx, edxbefore unsigned division. -
"
INT64_MIN / -1is a valid operation."
Fact:idivwithrax = 0x8000000000000000andrcx = -1raises#DE, deliveringSIGFPE.
Cause: the positive quotient2^63cannot be represented inint64_t.
Fix: guard against this boundary pair before executingidivand handle it explicitly. -
"
xor edx, edxis enough beforeidiv."
Fact: clearingrdxfor a negative dividend produces the wrong quotient or raises#DE.
Cause: a negative dividend’s sign must be extended across the fullrdx:raxpair.
Fix: executecqobefore 64-bitidiv, andcdqbefore 32-bitidiv. -
“You can ignore the high half of a product.”
Fact:UINT64_MAX * UINT64_MAXsetsrax = 1andrdx = 0xfffffffffffffffe; ignoringrdxmakes the product look like1.
Cause:mulalways writes 128 bits, andraxholds only the low 64 bits.
Fix: capture both halves and propagate carries if you need the full multi-word result.
Lab
Goal. Write asm_u128_to_dec(uint64_t hi, uint64_t lo, char *buf) to format a full 128-bit unsigned integer as a decimal string.
Contract and requirements.
- Inputs: high half, low half, and a buffer of at least 40 bytes.
- Output: string length excluding the null terminator;
buf[length] = 0. 0formats as"0".- Intermediate division by 10 must never raise
#DEfor any input.
Verification criteria.
make -C lessons/15-128bit-arithmetic build testpasses.hi = 0, lo = 0yields"0";hi = 1, lo = 0yields"18446744073709551616".hi = 0xffffffffffffffff, lo = 0xffffffffffffffffyields"340282366920938463463374607431768211455".gdb -q --nx -batch -ex 'break asm_u128_to_dec' -ex run -ex 'info registers rdi rsi rdx'verifies the ABI on entry:rdi = hi,rsi = lo,rdx = buf. Inspect therdx:raxpair separately inside the loop beforediv: break on thedivline in your.asm(or on the loop label) and runinfo registers rdx rax—that shows the live 128-bit dividend rather than the entry arguments.
Hints, expected output, and walkthrough
Dividing a 128-bit integer by 10 extracts one digit per iteration, relying on the fact that div divides the rdx:rax pair rather than a single register. The outer loop runs while hi != 0 || lo != 0, dividing the pair in two steps:
xor edx, edx,mov rax, hi,mov ecx, 10,div rcx— the divisor lives in a register becausedivhas no immediate operand form. The quotient overwriteshi, and the remainder stays inrdx(strictly less than 10 by definition).mov rax, lo,div rcx— reusingrdxdirectly from step 1. The quotient overwriteslo, and the new remainderrdxin0..9becomes the next decimal digit.
Step 1: [ 0 : hi ] ÷ 10 ──► q_hi, rem1 (< 10)
Step 2: [ rem1 : lo ] ÷ 10 ──► q_lo, digit (0..9)#DE is mathematically impossible here: the remainder from step 1 is smaller than the divisor (rdx < 10), so step 2’s dividend is strictly less than , guaranteeing the quotient fits in 64 bits. The only way to trigger #DE is feeding rdx >= 10 into div, which the two-step scheme never does.
Digits again emerge least-significant first, so reverse the buffer at the end. For hi = 1, lo = 0, the first digit produced is 6, the last is 1, and there are 20 digits in total.
Trying to run a single div directly with rdx = 0xffffffffffffffff triggers #DE immediately because the quotient overflows 64 bits. Always step from the high half down to the low half, carrying the remainder across.
Testbed sources, Makefile, and automated tests for this lesson: lessons/15-128bit-arithmetic.
Summary
mulwrites the full 128-bit product intordx:rax(high 64 bits inrdx, low 64 bits inrax).divandidivread the dividend from therdx:raxpair, neverraxalone.- Zero
rdxbefore unsigneddiv, and sign-extend withcqobefore signedidiv. - Any quotient that overflows 64 bits raises hardware exception
#DE. - Linux delivers
#DEasSIGFPE, even when no floating-point numbers are involved. - Exit code
136indicates termination bySIGFPE, not a program return value.
x87 stack, and flat SSE2 registers.