aython

Chapter 1 of 1130 min read

x86-64 in fifteen minutes

The registers, instructions, stack and calling convention the rest of the report leans on, taught from the assembly aython actually emits.

The rest of this report reads x86-64 assembly: the code aython generates for a program, and the 16,217-line runtime it calls. This chapter teaches the part of the machine that reading needs, and nothing else: the registers, the dozen instructions that do most of the work, the stack, the calling convention that lets generated code and hand-written helpers call each other, how a text file becomes a running process, and the flag that turns an integer overflow into a clean error.

Every example below is cut from the repository at build time: from runtime.s, or from the assembly the real frontend and code generator emit for a program in the test corpus. Nothing on this page was run on an x86-64 machine to make it; where the page says what a program prints, that is what CPython prints for it, which the judge requires the executable to match byte for byte.

Registers #

The processor computes on registers: sixteen named 64-bit slots, plus an instruction pointer rip that says which instruction runs next. Memory is far larger and far slower, so code loads a value into a register, works on it there, and stores the result back. In aython, a register almost always holds one of two things: a pointer to a Python object, or a raw 64-bit number on its way into or out of one.

The names are historical, and most registers have a job by convention rather than by hardware:

Register Role in aython Where you see it
rax A helper’s return value; scratch Every helper returns its new object here
rdi, rsi, rdx, rcx, r8, r9 Arguments one to six, in that order int_add gets its operands in rdi and rsi
r10, r11 Scratch; generated code passes the argument count of a user-function call in r10d mov r10d, 1 before call fn_fib
rbx, r12 to r15 Values that must survive calls; whoever uses them restores them int_add keeps its left operand in rbx, its right in r12
rbp The frame base: fixed for the duration of a function, so locals live at fixed offsets from it [rbp-8] is the first variable’s slot
rsp The stack pointer: the lowest address in use on the stack Moved by push, pop, call, ret, sub rsp, add rsp
xmm0, xmm1, … 128-bit registers used for floating point Float helpers do their arithmetic here, and pass doubles to libc’s pow

Each 64-bit register also has smaller names for its low bits: eax is the low 32 bits of rax, r10d of r10, al the low 8 bits of rax. One rule about them matters for reading: writing a 32-bit name clears the upper 32 bits of the full register. That is why xor eax, eax is the usual way to set all of rax to zero, and why mov r10d, 7 leaves exactly 7 in r10.

Reading one line of Intel syntax #

GNU as accepts two spellings of x86 assembly. Every assembly file here starts with .intel_syntax noprefix, which selects the Intel order (destination first) and drops the % and $ prefixes of the older AT&T style. A line reads like an assignment, right to left:

mov rax, [rbx + 16]  # rax gets left boxed value

Square brackets mean memory: [rbx + 16] is the 8 bytes at the address in rbx plus 16. Here rbx points at an int object and offset 16 is where its value lives (the next chapter draws every such layout). When the size of a memory operand cannot be inferred from a register, it is written out: inc qword ptr [rdi] adds one to the 8-byte reference count at the address in rdi. Everything after # is a comment. The code generator writes one on every line it emits, saying what the line does and, where ownership moves, whose reference is whose.

That is enough syntax to read the runtime’s first allocating helper. int_new turns a raw number in rdi into a pointer to an int object in rax:

runtime.s · int_newlines 753–789# ---- int_new ----------------------------------------------------------
# Input: rdi = i64 value. Output: rax = new owned int.
.p2align 4  # align function to 16 bytes
.globl int_new  # make int_new visible to linker
.type int_new, @function  # declare int_new as function
int_new:  # entry, rdi holds raw int64 value
    cmp rdi, -5  # below the cached range?
    jl intnew_alloc  # uncached negatives allocate fresh below
    cmp rdi, 256  # above the cached range?
    jg intnew_alloc  # uncached positives allocate fresh below
    lea rax, [rdi + 5]  # rax = cache index 0..261 for value -5..256
    imul rax, rax, 24  # rax = byte offset into the table (24 bytes each)
    lea rcx, [rip + small_ints]  # rcx = cache base (rip+index is illegal)
    add rax, rcx  # rax = cached immortal int, no alloc and no free ever
    ret  # return the shared singleton, like CPython's small-int cache
intnew_alloc:  # uncached value: fall into the bump/free-list path
    push rbp  # save rbp for frame chain
    mov rbp, rsp  # rbp marks this frame
    push rbx  # save rbx, holds value (the only callee-saved reg this path uses; two pushes keep 16-alignment)
    mov rbx, rdi  # rbx keeps value across alloc
    mov rax, [rip + free_int_head]  # rax gets int free list head
    test rax, rax  # check if a recycled header is waiting
    jz intnew_bump  # bump-allocate when the free list is empty
    mov rcx, [rax + 16]  # rcx gets next free link from payload slot
    mov [rip + free_int_head], rcx  # pop the head off the free list
    jmp intnew_fill  # skip bump path, fill the recycled block
intnew_bump:  # bump path for fresh 24 bytes
    mov rdi, 24  # rdi gets 24 byte int size
    call alloc_raw  # get fresh bytes from arena
intnew_fill:  # fill reused or fresh block
    mov qword ptr [rax], 1  # set refcnt 1, one owned reference
    lea rcx, [rip + type_int]  # rcx gets address of int tag
    mov [rax + 8], rcx  # store int type at offset 8
    mov [rax + 16], rbx  # store boxed value at offset 16
    pop rbx  # restore rbx
    pop rbp  # restore rbp
    ret  # return new owned int in rax

Almost every instruction aython uses appears in a handful of forms:

Instruction What it does Example in the repository
mov a, b Copy b into a; one side may be memory mov [rax + 16], rbx in int_new stores the value
movabs r, imm Load a full 64-bit constant (mov takes at most 32 bits, sign-extended) movabs rdi, 10 boxes the literal 10; movabs rcx, SENTINEL
lea r, [addr] Compute an address without reading memory lea rax, [rdi + 5] in int_new is arithmetic, not a load
add, sub, imul, inc, dec, neg Arithmetic, in place on the destination imul rax, rax, 24: multiply by the 24-byte entry size
cmp a, b, test a, b Compute a - b (or a & b), keep only the flags cmp rdi, -5 before the signed jump jl
jmp, je, jne, jl, jg, jae, ja, jo, … Jump always, or if the flags say so jl intnew_alloc: below the cache range
push r, pop r Move rsp down 8 and store; load and move rsp up 8 Every prologue starts push rbp
call f, ret Push the return address and jump; pop it and jump back call int_new, then ret at its end
cqo, idiv r Sign-extend rax into rdx:rax; divide, quotient in rax, remainder in rdx int_floordiv, int_mod
rep movsq, rep stosq Copy, or fill, rcx 8-byte words from [rsi] to [rdi] list_append copies the old item buffer when it grows

Sections and addresses #

An assembly file is a list of things to put in memory, sorted into sections that the linker groups and the loader maps with different permissions:

Section Permissions What aython puts there
.text Read, execute All code: the runtime’s helpers and the generated main_main and fn_* functions
.data Read, write The type tags, the singletons None, True, False, the empty tuple, and the cache of small ints
.bss Read, write, zero-filled, no space in the file The arena pointers, the free-list heads, the depth guards, the exception handler stack, saved argc/argv, default-argument statics
.rodata Read only Error messages, the words None/True/False, punctuation for printing, float constants, the generated string-literal pool

Code refers to anything in these sections relative to rip: lea rcx, [rip + type_int] (the runtime’s spelling) or lea rax, aython_none[rip] (the generated code’s) means “the address of type_int, as an offset from this instruction”. The assembler and linker fill in the distance, so the code works wherever the loader places the executable. One limit shows up repeatedly in the runtime: a rip-relative operand cannot also take an index register, so a table lookup first loads the table’s address and then indexes it. int_new does exactly this for the small-int cache, and says so in its comment: lea rcx, [rip + small_ints] # rcx = cache base (rip+index is illegal).

Memory is little-endian: the 8-byte number 0x0000000000000001 is stored as the byte 01 followed by seven zero bytes. This only becomes visible when one looks at bytes rather than numbers, as the type tags do.

The stack #

The stack is a region of memory the process gets from the kernel at start-up, used as last-in, first-out scratch space. It grows downwards: push rax subtracts 8 from rsp and stores rax at the new rsp; pop rax loads from rsp and adds 8. Everything above rsp is in use; everything below it is free.

call f is a push and a jump: it pushes the address of the instruction after itself, the return address, and jumps to f. ret pops that address and jumps to it. So at the first instruction of any function, [rsp] holds the address to return to, and the function’s job is to leave rsp exactly there when it executes ret.

A function that needs memory of its own builds a frame on the stack. Every function aython generates builds it the same way, in three instructions:

tests/mvp/pass_fn_fib.py · emitted · fn_fibpush rbp  # save the caller's frame base on the stack
mov rbp, rsp  # our frame base = current stack top
sub rsp, 1872  # carve all variable + temp slots at once (fixed size)

push rbp saves the caller’s frame base; mov rbp, rsp makes the current stack top this function’s frame base; sub rsp, N reserves N bytes below it in one step. From then on rbp does not move, and every local lives at a fixed negative offset from it. Seen from inside the function:

higher addresses
  [rbp+24]   argument 1      (only when a call passes arguments on the stack)
  [rbp+16]   argument 0
  [rbp+8]    return address  pushed by the caller's call
  [rbp]      caller's rbp    pushed by push rbp
  [rbp-8]    slot 0          the first parameter or variable
  [rbp-16]   slot 1
  ...        the return-value slot (functions only), then temporaries
  [rsp]      the frame's lowest address, after sub rsp, N
lower addresses

The epilogue undoes it as directly. mov rsp, rbp discards the whole frame at once, pop rbp restores the caller’s frame base, and ret returns.

How big codegen makes a frame #

The code generator does not track how many temporaries an expression needs. It reserves a safe upper bound once, and never moves rsp again until the epilogue. The layout is a frozen dataclass:

src/aython/codegen.py · Framelines 414–427@dataclass(frozen=True)
class Frame:
    """Read-only frame layout for one program or function.

    Args:
        var_index: Mapping of variable name to 0-based slot number.
        nvars: Number of variable slots in the frame.
        reserved: Extra hidden slots above the variables (the function
            return-value slot); expression temps start above those.
    """

    var_index: dict[str, int]
    nvars: int
    reserved: int = 0

and the size is computed from the number of nodes in the program’s syntax tree:

src/aython/codegen.py · _frame_byteslines 484–497def _frame_bytes(tree: ast.Module, frame: Frame) -> int:
    """Compute the fixed frame size for a body of statements.

    Args:
        tree: Module whose nodes size the temp area (a safe upper bound
            shared by main and every function frame).
        frame: Frame layout with variable and reserved slots.

    Returns:
        16-aligned byte count to subtract from ``rsp`` once.
    """
    total_nodes = sum(1 for _ in ast.walk(tree))
    temp_slots = SLOTS_PER_NODE * total_nodes + SPARE_SLOTS + EXC_SAVE_SLOTS
    return _align_up((frame.nvars + frame.reserved + temp_slots) * WORD_SIZE, FRAME_ALIGN)

That is 4 slots per AST node, 8 spare, 64 reserved for saved exception kinds (one per possible try nesting level), plus the variables, all rounded up to a multiple of 16. The bound is generous: pass_fn_fib.py is six lines, and its fib reserves 1872 bytes, of which it names two slots. Stack memory costs nothing until it is touched, and a fixed frame buys two things: every slot and temporary has an address known at compile time, and rsp is the same at every call the function makes. Why the second matters is the next section.

The calling convention #

Generated code calls runtime helpers, helpers call each other, and both call libc. That only works if every caller and every callee agree on where arguments go and which registers survive a call. aython uses the System V AMD64 ABI, the convention every compiler on Linux uses, so the same rules also govern its calls into libc:

Rule Consequence in aython
Integer and pointer arguments go in rdi, rsi, rdx, rcx, r8, r9; more go on the stack A helper with three object arguments, such as obj_setitem, takes them in rdi, rsi, rdx
The result comes back in rax Every helper returns its new object in rax; generated code stores it into a slot at once
rax, rcx, rdx, rsi, rdi, r8 to r11 are caller-saved: a call may change them Generated code keeps nothing in registers across a call; every value lives in a frame slot
rbx, rbp, r12 to r15 are callee-saved: a function that uses them restores them Helpers open with push rbx, push r12, … and pop them in reverse before ret
rsp is a multiple of 16 at every call (so it is 8 more than a multiple of 16 at a function’s first instruction) Some library code stores 16-byte values to the stack with instructions that fault when the address is misaligned
The direction flag is clear on entry and exit rep movsq copies forwards; helpers that copy say cld first anyway

User functions follow the same register order. The constant that says so in the code generator:

src/aython/codegen.py · REG_ARG_ORDER, GENERAL_ARGClines 60–73# Argument-passing registers for user-function calls, in SysV order.
# A call with this many arguments or fewer carries every argument in
# these registers (the count still travels in ``r10d``); wider calls
# keep the legacy stack layout. Both sides branch on the same length
# test against the same tuple, and the callee checks arity before
# adopting, so a mismatched call aborts before touching either layout.
# Flexible calls (any keyword, ``*``/``**`` unpacking, or a flexible
# callee) use the general mode instead: the caller builds an owned
# positional list plus an owned keyword dict, passes them in
# ``rdi``/``rsi`` with ``r10d = -1``, and the callee binds them to its
# params (adopting both containers). ``-1`` never collides with a real
# argc, which is always non-negative.
REG_ARG_ORDER = ("rdi", "rsi", "rdx", "rcx", "r8", "r9")
GENERAL_ARGC = -1

A call with up to six arguments evaluates each into a temporary slot, moves them into rdi, rsi, … in order, puts the count in r10d, and calls. Here is print(fib(10)) calling fib:

tests/mvp/pass_fn_fib.py · emitted · main_mainmovabs rdi, 10  # arg = raw integer value (not a pointer yet)
call int_new  # rax = new owned int box (refcnt 1)
mov [rbp-16], rax  # park owned arg0
mov rdi, [rbp-16]  # arg0 -> register (owned ref travels with it)
mov r10d, 1  # argc for the callee's arity check
call fn_fib  # rax = owned result; args adopted, not borrowed
mov [rbp-8], rax  # park the owned argument across the print call
mov rdi, [rbp-8]  # arg = value to spell out (helper borrows it)
call aython_print_obj  # write the repr bytes to stdout
mov rdi, [rbp-8]  # arg = same value, now to release
call aython_decref  # argument was single-use; usually freed here

The callee checks the count first, so a wrong number of arguments aborts with TypeError the way CPython raises it, and then adopts each argument: it stores the pointer in its own slot without counting a new reference, because the caller’s reference travels with the call. (r10d = -1 marks the general mode used for keywords and *args, where the caller passes a list and a dict instead; the codegen chapter covers it.)

tests/mvp/pass_fn_fib.py · emitted · fn_fib# adopt params: caller passed arg0..arg0 in registers, count in r10d
cmp r10d, 1  # arity check first: CPython raises TypeError here
jne abort_type  # shared runtime stub: one stderr line, exit 1
mov [rbp-8], rdi  # arg0: caller's owned ref, adopted not increfed

With seven or more arguments the registers run out, and every argument goes on the stack instead. The caller pushes them last to first, so argument 0 ends up nearest the return address, at [rbp+16] in the callee. Seven pushes are 56 bytes, which would leave rsp 8 bytes off a multiple of 16 at the call, so an odd count is padded first. After the call the caller removes what it pushed:

tests/mvp/pass_fn_wide.py · emitted · main_mainsub rsp, 8  # pad: odd arg count would misalign rsp at call
push qword ptr [rbp-64]  # arg6 (reverse: arg0 deepest)
push qword ptr [rbp-56]  # arg5 (reverse: arg0 deepest)
push qword ptr [rbp-48]  # arg4 (reverse: arg0 deepest)
push qword ptr [rbp-40]  # arg3 (reverse: arg0 deepest)
push qword ptr [rbp-32]  # arg2 (reverse: arg0 deepest)
push qword ptr [rbp-24]  # arg1 (reverse: arg0 deepest)
push qword ptr [rbp-16]  # arg0 (reverse: arg0 deepest)
mov r10d, 7  # argc for the callee's arity check
call fn_add7  # rax = owned result; args adopted, not borrowed
add rsp, 64  # drop our arg slots (ownership already transferred)

That is the whole of _emit_fast_call’s stack path: pad first, push in reverse, call, clean up 8 × (n + n mod 2) bytes.

src/aython/codegen.py · _emit_fast_calllines 2605–2665def _emit_fast_call(
    name: str,
    args: list[ast.expr],
    frame: Frame,
    depth: int,
    leading: tuple[str, ...] = (),
) -> list[str]:
    """Emit the register/stack fast path for a positional-only call.

    Args:
        name: Validated function name in the global table.
        args: Already-validated positional argument expressions.
        frame: Caller frame layout for slots and temps.
        depth: Temp base; one slot per argument above it.
        leading: Already-parked owned operands travelling first (the
            instance for an ``__init__`` call); they sit outside
            ``[depth, ...)`` and move straight into registers or stack
            slots ahead of the evaluated arguments.

    Returns:
        Assembly lines leaving the owned result in rax.
    """
    n_site = len(args)
    n = n_site + len(leading)
    lines = [f"# call {name}(...) ({n} args in registers, count in r10d)"]
    sub = depth + n + 1
    for i, arg in enumerate(args):
        assert not isinstance(arg, ast.Starred)
        lines += _emit_expr(arg, frame, sub)
        lines.append(f"mov {_temp(frame, depth + i)}, rax  # park owned arg{i}")
    operands = list(leading) + [_temp(frame, depth + i) for i in range(n_site)]
    if n <= len(REG_ARG_ORDER):
        # Registers are caller-saved and no call sits between these
        # moves and the call, so the args survive intact. rsp never
        # moves, so no pad and no cleanup: alignment holds by itself.
        for i in range(n):
            lines.append(f"mov {REG_ARG_ORDER[i]}, {operands[i]}  # arg{i} -> register (owned ref travels with it)")
        lines += [
            f"mov r10d, {n}  # argc for the callee's arity check",
            f"call {_fn_sym(name)}  # rax = owned result; args adopted, not borrowed",
        ]
        return lines
    lines[0] = f"# call {name}(...) ({n} args on the stack, count in r10d)"
    lines += [
        "# wide call: register file exhausted, falling back to the stack layout",
    ]
    # Pad FIRST so the args always sit directly above the return address:
    # [rbp+16+8*i] is arg i regardless of parity. Padding after the pushes
    # would wedge a dead slot between the return address and arg0.
    if n % 2 == 1:
        lines.append("sub rsp, 8  # pad: odd arg count would misalign rsp at call")
    for i in range(n - 1, -1, -1):
        lines.append(f"push qword ptr {operands[i]}  # arg{i} (reverse: arg0 deepest)")
    lines += [
        f"mov r10d, {n}  # argc for the callee's arity check",
        f"call {_fn_sym(name)}  # rax = owned result; args adopted, not borrowed",
    ]
    cleanup = 8 * (n + n % 2)
    if cleanup:
        lines.append(f"add rsp, {cleanup}  # drop our arg slots (ownership already transferred)")
    return lines

Stepping through a call #

The figure below replays two real call sequences instruction by instruction, from the moment crt calls the runtime’s main. Each step shows the registers and the live stack, and at every call it shows rsp modulo 16. The register call is fib(10) from pass_fn_fib.py; the stack call is add7(1, ..., 7) from pass_fn_wide.py.

Two real call sequences, replayed from the assembly codegen emits. Step with the buttons or the arrow keys and watch rsp: it is 8 off a multiple of 16 on entry to each function, back on one after push rbp, and on one at every call. Switch to add7 to see the pad, the seven pushes, the callee reading [rbp+16] upwards, and the caller's add rsp, 64. Addresses are illustrative; their differences and their values modulo 16 are fixed by the code. The function bodies are skipped.

Because a generated function reserves its frame in one sub of a multiple of 16 right after push rbp, rsp is a multiple of 16 for the function’s whole body. Every register call it makes is aligned with no further work, and only the stack-argument path needs the pad.

From text to a running process #

aython never produces machine code itself. It produces assembly text, and the standard toolchain does the rest:

flowchart TB
  py[prog.py] --> fe[frontend.py<br/>parse with ast, check the subset]
  fe --> cg[codegen.py<br/>emit Intel-syntax assembly]
  cg --> s[prog.s.gen]
  s --> as1[as] --> o1[prog.o]
  rt[runtime.s] --> as2[as] --> o2[runtime.o]
  o1 --> cc[cc ... -lm<br/>link with crt, libc, libm]
  o2 --> cc
  cc --> elf[prog.elf]
  elf --> run[crt _start → main → arena_init, main_main → exit 0]
  class fe,cg,rt accent
From a Python file to a process: the frontend and codegen run on the host; as and cc are the system's own assembler and C compiler driver; the ELF runs with no Python at all.

The judge’s build_program is that diagram in code: it runs the frontend and the code generator in-process, writes the assembly next to the source, assembles both files with as, and links with cc, adding libm because int_pow calls libc’s pow:

src/aython/judge.py · build_programlines 141–175def build_program(source: Path, runtime_src: Path) -> Path:
    """Compile a source file all the way to an ELF executable.

    Args:
        source: Program ``.py`` file; artifacts land beside it.
        runtime_src: Path to ``runtime.s`` providing ``main``/``arena_init``.

    Returns:
        Path to the linked ``.elf`` executable.

    Raises:
        frontend.FrontendError: If the program is outside the subset.
        subprocess.CalledProcessError: If assembly or linking fails.
    """
    # Resolve so artifact paths are absolute: the kernel execs the ELF
    # directly, and a bare relative name (no directory component) would
    # make execvp search PATH instead of the current directory.
    source = source.resolve()
    runtime_src = runtime_src.resolve()
    text = source.read_text(encoding="utf-8")
    tree, variables, funcs = frontend.compile_source(text, str(source))
    asm_text = codegen.generate(tree, variables, funcs)
    asm_path = source.with_suffix(ASM_SUFFIX)
    obj_path = source.with_suffix(OBJ_SUFFIX)
    elf_path = source.with_suffix(ELF_SUFFIX)
    runtime_obj = elf_path.parent / RUNTIME_OBJ_NAME
    asm_path.write_text(asm_text, encoding="utf-8")
    log.debug("wrote %s (%d vars)", asm_path, len(variables))
    subprocess.run([ASSEMBLER_CMD, "-o", str(obj_path), str(asm_path)], check=True)
    subprocess.run([ASSEMBLER_CMD, "-o", str(runtime_obj), str(runtime_src)], check=True)
    subprocess.run(
        [LINKER_CMD, "-o", str(elf_path), str(obj_path), str(runtime_obj), LINK_MATH_LIB],
        check=True,
    )
    return elf_path

cc adds the C runtime start-up files. Their _start is where the kernel begins executing the process; it hands control to libc’s start-up code, which initialises libc and calls main(argc, argv). main is the runtime’s, and it is short:

runtime.s · mainlines 13806–13860main:  # libc entry point: rdi = argc, rsi = argv, returns the exit status
    push rbp  # save crt's frame base (entry rsp % 16 == 8, now aligned)
    mov rbp, rsp  # frame base for the program body
    call arena_init  # stash args, mmap the arena (rdi/rsi pass through)
    call main_main  # run the generated program body
    xor eax, eax  # return status 0: success, crt exits the process
    pop rbp  # restore crt's frame base
    ret  # back to crt, which exits the process

arena_init saves argc and argv for the argv() builtin and asks the kernel for the 64 MiB memory arena every object will live in, through libc’s mmap (the next chapter is about that arena). Then main_main, the generated program, runs; when it returns, main returns 0 and libc exits the process with that status. The figure above starts at the first push rbp here.

Leaving early goes through one place. Every runtime error that no try catches ends at abort_msg, which writes one line to standard error and exits with status 1, through libc’s write and _exit:

runtime.s · abort_msglines 281–319abort_msg:  # shared abort entry point
    and rsp, -16  # noreturn: realign unconditionally (callers arrive
...
    mov rdx, rsi  # rdx gets message length from rsi
    mov rsi, rdi  # rsi gets message pointer from rdi
    mov rdi, 2  # rdi gets stderr fd 2
    call write  # write message to stderr via libc (errno ignored here)
    mov edi, 1  # rdi gets exit status 1
    call _exit  # terminate via libc, never returns
    ud2  # trap in case _exit ever returns

Why libc, and not system calls #

The original design said “no libc, only direct Linux system calls”: put the call number in rax and execute the syscall instruction, as a program with no C library at all would. The build now links against libc, and docs/core-design.md records why, in “What changed in the building (libc link)”:

Raw syscall (the first design) libc (what is built)
Process start-up The runtime’s own _start crt’s _start calls the runtime’s main(argc, argv)
Kernel calls Hand-written stubs per call, raw system-call numbers and argument registers (r10 for the fourth argument) write, mmap, open, read, close, _exit as ordinary function calls (rcx for the fourth argument)
Error reporting A negative error number in rax -1, with the error in errno (MAP_FAILED for mmap)
What stays hand-written Everything The allocator, the object layout, every helper, printing, the abort messages

The stubs had taught what they had to teach, and every new capability (file input, argv, the self-hosted tokenizer’s arena) was paying the system-call conventions again. The question the original rule protected, “where can behaviour hide?”, is answered by keeping all allocation and printing in hand-written code and letting libc own only start-up and the crossing into the kernel. The arena comment in arena_init shows the one place the difference is visible: cmp rax, -1 # libc signals failure with exactly -1, unlike raw -errno.

Flags, and the overflow check #

cmp, test and the arithmetic instructions leave their verdict in the flags register, a set of single bits that the conditional jumps read. Four matter here:

Flag Set when Read by
ZF, zero The result was 0 (for cmp a, b: a == b) je, jne, jz, jnz
SF, sign The result’s top bit is 1 (negative, read as signed) js, jns; with OF, jl, jg
CF, carry The result did not fit as an unsigned number jb, jae, ja, jc
OF, overflow The result did not fit as a signed number jo, jno; with SF, jl, jg

The same bits mean different things depending on which jump reads them, and the runtime chooses deliberately. int_new uses the signed jl/jg because -5 must compare below 256. aython_incref uses the unsigned jae against the immortal sentinel. alloc_raw uses jc to catch a request so large that adding it to the arena pointer wraps around.

A Python int has no upper limit; an aython int is one signed 64-bit register. The design decision, in the review table of docs/core-design.md, is “Boxed i64, abort OverflowError on overflow. No bigint in MVP”: a result that does not fit stops the program with a clear error instead of silently wrapping or growing into a big integer, which would need an allocator of its own. On x86-64 the check costs one instruction, because add, sub and imul set OF whenever the true result does not fit in 64 signed bits:

runtime.s · int_addlines 791–911    call check_intlike_rbx_r12  # both operands must be int-like; bools count as 1/0
.Ladd_compute:  # both sides int-like (fast path or validated slow path)
    mov rax, [rbx + 16]  # rax gets left boxed value
    add rax, [r12 + 16]  # add right boxed value, sets flags
    jo abort_overflow  # abort OverflowError on signed overflow
    mov rdi, rax  # rdi gets raw sum for int_new
    call int_new  # box sum as new owned int
    pop r15  # restore r15
    pop r14  # restore r14

int_mul is the same with imul rax, [r12 + 16]. The runtime has 53 such jo checks. Negation is the one operation where the runtime tests the value instead of a flag: -(-2**63) does not fit, so int_neg compares with INT64_MIN before negating. The corpus pins the behaviour with a program CPython runs happily and the executable must refuse:

tests/mvp/abort_overflow.pylines 1–4# mvp: abort:OverflowError
big = 4611686018427387904
y = big * 4
print(y)

Its first line is the judge’s expectation marker: the executable must exit non-zero with aython: OverflowError on standard error. 4611686018427387904 is 262, which fits; four times it does not. Where it differs from CPython lists this with the other divergences.

Where this lives #

Concept Where
Register use, calling convention, libc calls, in the runtime’s own words runtime.s, header comment
The program entry: crt calls main, which maps the arena and calls main_main runtime.s main, arena_init
Frame layout and size src/aython/codegen.py Frame, _frame_bytes, _slot, _temp, _ret_slot
Prologue and epilogue src/aython/codegen.py _prologue_lines, _epilogue_lines, _emit_function
Register and stack calls between generated functions src/aython/codegen.py REG_ARG_ORDER, GENERAL_ARGC, _emit_fast_call
Assembling and linking src/aython/judge.py build_program, ASSEMBLER_CMD, LINKER_CMD, LINK_MATH_LIB
The single exit for errors runtime.s abort_msg, exc_check
Overflow checks runtime.s int_add, int_sub, int_mul, int_neg; tests/mvp/abort_overflow.py
Why libc docs/core-design.md, “What changed in the building (libc link)”
The call-frame figure docsite/figures/machine.py, docsite/static/widgets/callframe.js

Check yourself #

Check yourself

  1. int_add starts with push rbp and then pushes rbx, r12, r13, r14 and r15. It was called with rsp a multiple of 16. What is rsp modulo 16 when it executes call int_new?

    1. 0
    2. 8
    3. It depends on the operands
    Answer8. The call into int_add pushed 8 bytes, so it starts at 8 modulo 16. Six pushes are 48 bytes, a multiple of 16, which keeps it at 8. That is harmless because int_new never depends on alignment; it is also why helpers that call libc pad with sub rsp, 8.
  2. add7 takes seven arguments. Inside fn_add7, where is argument 0?

    1. In rdi
    2. At [rbp+16]
    3. At [rbp-8], where the caller stored it
    AnswerAt [rbp+16]. Past six arguments every argument goes on the stack, pushed last to first. Above rbp sit the saved rbp at [rbp] and the return address at [rbp+8], so argument 0 is at [rbp+16], argument 1 at [rbp+24], and so on. The callee then copies each into its own slot: [rbp-8] is the callee’s slot for a, not the caller’s.
  3. Why does a register call like fib(n - 1) never need a sub rsp, 8 pad?

    1. Because it passes an even number of arguments
    2. Because the function’s frame is reserved once, in a multiple of 16 right after push rbp, and rsp does not move again
    3. Because call aligns the stack itself
    AnswerBecause the function’s frame is reserved once, in a multiple of 16 right after push rbp, and rsp does not move again. Entry leaves rsp 8 off; push rbp makes it a multiple of 16; sub rsp, N with N a multiple of 16 keeps it there for the whole body. Only pushes of stack arguments move rsp mid-function, which is why only that path pads.
  4. big = 2**62 fits in a signed 64-bit register. What does big * 4 do in an aython program?

    1. Wraps around to 0, as C would
    2. Prints 18446744073709551616, as CPython does
    3. Aborts with aython: OverflowError, because imul sets the overflow flag and jo abort_overflow takes it
    AnswerAborts with aython: OverflowError, because imul sets the overflow flag and jo abort_overflow takes it. aython ints are one signed 64-bit word by design. imul sets OF when the true product does not fit, and the next instruction jumps to the abort. CPython would print the big integer; tests/mvp/abort_overflow.py pins the difference.
  5. The original design called the kernel with raw syscall instructions. What does linking with libc change for the runtime?

    1. The allocator and printing move into libc
    2. crt provides the process entry and calls main; kernel calls become ordinary calls to write, mmap and the rest, which report errors as -1 with errno
    3. Nothing; libc is only used for pow
    Answercrt provides the process entry and calls main; kernel calls become ordinary calls to write, mmap and the rest, which report errors as -1 with errno. Only start-up and the crossing into the kernel moved. The arena, free lists, object layouts, helpers and abort messages are still hand-written in runtime.s; the error convention changed from a negative errno to -1, as arena_init’s cmp rax, -1 shows.