On this page

mul returns 128 bits across two registers, while div expects a 128-bit dividend—one stale rdx is enough to raise SIGFPE.

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.

mul128.asm
; 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 progbits

In 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                   	ret
  • mov rax, rdi sets up the first factor, because mul always reads rax.
  • mov r8, rdx saves the hi pointer before mul clobbers rdx.
  • mul rsi multiplies rax by rsi and writes all 128 bits into rdx:rax.
  • mov QWORD PTR [r8], rdx stores the high half through r8.

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

0x1fffffffffffffffe\mathtt{0x1fffffffffffffffe} 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                   	ret
  • mov rax, rsi loads the low half of the dividend into rax.
  • mov rdx, rdi loads the high half into rdx; without this, div would divide garbage in rdx.
  • div r8 divides rdx:rax by the divisor and leaves the remainder in rdx.
  • mov [r9], rdx writes the remainder through r9.

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                   	ret

48 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:

divbug.asm
; 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 progbits
  • dirty mode sets rdx = 2 and divides by 2: (2 * 2^64) / 2 doesn’t fit in 64 bits, so div raises #DE.
  • min mode divides INT64_MIN by -1: the quotient 2^63 overflows signed 64 bits.
  • ok mode runs idiv with valid operands and exits with 14.

Exit codes tell the outcomes apart:

$ ./build/divbug ok; echo $?
14
$ ./build/divbug dirty; echo $?
136
$ ./build/divbug min; echo $?
136

136 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 — stale 2 in rdx; dividing by 2 requires rdx = 0.
  • $2 — rax = 0, the low half of the dividend, harmless on its own.
  • $3 — divisor in rcx.
  • div rcx — the faulting instruction; rip still points to it because #DE is 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: cqo extended rax’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

  1. "div crashes on an ordinary number."
    Fact: with rdx = 2 and rcx = 2, div rcx terminates the process with exit code 136.
    Cause: div reads the dividend from rdx:rax, not rax alone; a non-zero rdx makes the dividend huge.
    Fix: clear rdx with xor edx, edx before unsigned division.

  2. "INT64_MIN / -1 is a valid operation."
    Fact: idiv with rax = 0x8000000000000000 and rcx = -1 raises #DE, delivering SIGFPE.
    Cause: the positive quotient 2^63 cannot be represented in int64_t.
    Fix: guard against this boundary pair before executing idiv and handle it explicitly.

  3. "xor edx, edx is enough before idiv."
    Fact: clearing rdx for a negative dividend produces the wrong quotient or raises #DE.
    Cause: a negative dividend’s sign must be extended across the full rdx:rax pair.
    Fix: execute cqo before 64-bit idiv, and cdq before 32-bit idiv.

  4. “You can ignore the high half of a product.”
    Fact: UINT64_MAX * UINT64_MAX sets rax = 1 and rdx = 0xfffffffffffffffe; ignoring rdx makes the product look like 1.
    Cause: mul always writes 128 bits, and rax holds 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.
  • 0 formats as "0".
  • Intermediate division by 10 must never raise #DE for any input.

Verification criteria.

  1. make -C lessons/15-128bit-arithmetic build test passes.
  2. hi = 0, lo = 0 yields "0"; hi = 1, lo = 0 yields "18446744073709551616".
  3. hi = 0xffffffffffffffff, lo = 0xffffffffffffffff yields "340282366920938463463374607431768211455".
  4. 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 the rdx:rax pair separately inside the loop before div: break on the div line in your .asm (or on the loop label) and run info 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:

  1. xor edx, edx, mov rax, hi, mov ecx, 10, div rcx — the divisor lives in a register because div has no immediate operand form. The quotient overwrites hi, and the remainder stays in rdx (strictly less than 10 by definition).
  2. mov rax, lo, div rcx — reusing rdx directly from step 1. The quotient overwrites lo, and the new remainder rdx in 0..9 becomes 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 rdx⋅264+lordx \cdot 2^{64} + lo is strictly less than 10⋅26410 \cdot 2^{64}, 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

  1. mul writes the full 128-bit product into rdx:rax (high 64 bits in rdx, low 64 bits in rax).
  2. div and idiv read the dividend from the rdx:rax pair, never rax alone.
  3. Zero rdx before unsigned div, and sign-extend with cqo before signed idiv.
  4. Any quotient that overflows 64 bits raises hardware exception #DE.
  5. Linux delivers #DE as SIGFPE, even when no floating-point numbers are involved.
  6. Exit code 136 indicates termination by SIGFPE, not a program return value.
Bridge to the Next Lesson
Integer math pushed up against 64 bits while staying exact. In lesson 16, we enter the world where precision gives out: IEEE 754 representation, the 80-bit x87 stack, and flat SSE2 registers.