Skip to content

Instantly share code, notes, and snippets.

@michidk
Last active October 10, 2026 13:22
Show Gist options
  • Select an option

  • Save michidk/a3dcf2b921d627416d6579d45e12ddc1 to your computer and use it in GitHub Desktop.

Select an option

Save michidk/a3dcf2b921d627416d6579d45e12ddc1 to your computer and use it in GitHub Desktop.
Small Rust and Zig Hello World: 153-byte naked assembly on stable Rust and Zig, 157-byte Zig syscall wrappers; complete sources, Cargo config and verified builds

Small Rust and Zig Hello World

Complete executable sizes, verified on x86-64 Linux:

Source and build Bytes Dependencies
hello-safe.rs: no unsafe code, println! 286,392 Shared libc and system libraries
hello-no-asm.rs: unsafe libc calls, no handwritten assembly 984 Shared libc and dynamic loader
hello.rs: inline syscalls, default linker script, rustc or Cargo 209 None
hello.rs: inline syscalls, Cargo with minimal.ld 153 None
hello.zig: Zig Linux syscall wrappers, default GNU ld script 213 None
hello.zig: Zig Linux syscall wrappers, minimal.ld 157 None
hello-inline.zig: Zig inline syscalls, default GNU ld script 209 None
hello-inline.zig: Zig inline syscalls, minimal.ld 153 None

Shared libraries are excluded from file sizes. Builds use the default linker script unless minimal.ld is named. All executable files are direct linker output: no packer or metadata trimming afterward.

With direct rustc builds and no size optimizations, Rust 1.98.1 produces 4,506,168 bytes for hello-safe.rs and 1,616 bytes for hello.rs. The latter requires -Cpanic=abort, -Crelocation-model=static, -Clink-arg=-nostartfiles, and -Clink-arg=-static. These select its panic strategy, fixed-address code, custom entry point, and direct loading without a dynamic interpreter; they are not default flags. This unoptimized build uses Rust's default LLD selection; optimized builds use GNU ld.

Rust: rustc 1.98.1 (48a229cea 2026-09-01), toolchain 1.98.1, target x86_64-unknown-linux-gnu, edition 2024.

Zig: 0.17.0, target x86_64-linux, optimization mode small, LLVM backend. Compiler downloads: ziglang.org.

Requires Python 3, rustup, GCC, GNU binutils with -z nosectionheader, and x86-64 Linux. Tested with GNU ld 2.47.20260726; other compiler/linker versions may produce different sizes.

The Zig builds additionally require Zig 0.17.0.

rustup toolchain install 1.98.1 --profile minimal
python3 build.py
./out/rust-safe
./out/rust-no-asm
./out/rust-cargo-minimal
sh build-zig.sh
./out/hello-minimal
./out/hello-inline-minimal

hello-safe.rs uses no unsafe code and uses Rust's standard library. The other sources use no_std and no_main. hello-no-asm.rs calls libc's puts and exit; its aligned volatile local makes Rust align the entry-point stack before those calls. hello.rs uses a #[unsafe(naked)] entry point and naked_asm! for its complete instruction sequence. Linux supplies zero initial RAX, RBX, and RDX; mov al, 1, mov dl, 14, and the two xchg instructions use those values. The compiler emits no prologue, epilogue, or trailing trap. The entry point must be loaded directly by Linux, with no dynamic interpreter.

hello.zig uses Zig's standard-library Linux syscall wrappers and contains no handwritten assembly. Its generated code still initializes registers explicitly; these wrappers do not express the known initial register values or the desired register exchanges. It remains 157 bytes with minimal.ld. hello-inline.zig uses callconv(.naked) and the same instruction sequence as the handwritten assembly and naked Rust, taking 19 bytes. Linker layouts and message addresses differ; the complete executables are not byte-identical. Both Zig sources use a 14-byte array to omit the string literal's trailing null byte. The inline versions are assembly implementations hosted in Rust/Zig, not compiler-generated equivalents.

All versions print Hello, World!\n and exit 0 when writing succeeds. The naked Rust/Zig versions and the Zig syscall-wrapper version also exit 0 after a returned write error. The two exchanges set the exit number and status independently of the write result; they no longer assume a successful write. The safe Rust version may panic on an output error. Syscall versions do not retry partial writes or suppress signals such as SIGPIPE. Standard and system libraries contain their own unsafe code.

minimal.ld preserves complete, separate ELF and program headers. No header bytes contain instructions. GNU ld omits section headers using -z nosectionheader. The Python script builds, copies Cargo outputs unchanged into out/, and checks exact output, exit status, extra arguments, and an empty environment for Rust. It also checks returned ENOSPC and EBADF errors for the naked Rust builds. build-zig.sh builds Zig with both GNU ld layouts using the same minimal.ld. Zig outputs were also verified for exact output, exit 0, extra arguments, and an empty environment. Both Zig versions were checked for exit 0 after returned write errors. All tiny syscall variants were checked with a broken pipe and SIGPIPE ignored so that EPIPE is returned rather than terminating the process. These are measured results, not proven minima.

ZIG can select a local Zig compiler path. Based on The Smallest Hello World Program.

Unoptimized reference commands (run from the directory containing the sources):

rustup run 1.98.1 rustc hello-safe.rs --edition=2024 -o hello-safe
rustup run 1.98.1 rustc hello.rs --edition=2024 -Cpanic=abort -Crelocation-model=static -Clink-arg=-nostartfiles -Clink-arg=-static -o hello

For Cargo, save config.toml as .cargo/config.toml, then run cargo build --release. Add the commented linker-script flag to use minimal.ld. Ordinary cargo build uses the dev profile and does not produce the measured release sizes.

#!/bin/sh
set -eu
cd "$(dirname "$0")"
mkdir -p out
zig_bin="${ZIG:-zig}"
for name in hello hello-inline; do
"$zig_bin" build-obj "$name.zig" -target x86_64-linux -O small -fllvm \
-fstrip -fno-unwind-tables -fno-stack-protector -fomit-frame-pointer \
-fno-PIC -femit-bin="out/$name.o"
ld --gc-sections -s -z nosectionheader -z noseparate-code \
--no-eh-frame-hdr "out/$name.o" -o "out/$name-normal"
ld --gc-sections -s -z nosectionheader -T minimal.ld \
"out/$name.o" -o "out/$name-minimal"
done
wc -c out/hello-normal out/hello-minimal out/hello-inline-normal out/hello-inline-minimal
#!/usr/bin/env python3
import os
import subprocess
from pathlib import Path
os.chdir(Path(__file__).resolve().parent)
out = Path("out")
out.mkdir(exist_ok=True)
def run(*args, **kwargs):
subprocess.run(args, check=True, **kwargs)
def verify(path, errors=False):
path.chmod(0o755)
command = [str(path.resolve())]
for args, env in (([], None), (["extra", "arguments"], None), ([], {})):
result = subprocess.run(command + args, env=env, capture_output=True, timeout=2)
assert (result.returncode, result.stdout, result.stderr) == (0, b"Hello, World!\n", b"")
if errors:
with open("/dev/full", "wb") as full:
assert subprocess.run(command, stdout=full, timeout=2).returncode == 0
result = subprocess.run(["sh", "-c", 'exec "$1" 1>&-', "sh", *command],
capture_output=True, timeout=2)
assert (result.returncode, result.stdout, result.stderr) == (0, b"", b"")
print(f"{path.name}: {path.stat().st_size} bytes")
flags = ("--edition=2024 --target=x86_64-unknown-linux-gnu -Copt-level=z "
"-Cpanic=abort -Cforce-unwind-tables=no")
normal = ("-Cstrip=symbols -Clto=fat -Ccodegen-units=1 -Clinker-features=-lld "
"-Crelro-level=off -Clink-arg=-nostartfiles -Clink-arg=-static "
"-Clink-arg=-Wl,--build-id=none,-z,noseparate-code,-z,nosectionheader,"
"--no-eh-frame-hdr,--hash-style=sysv,--spare-dynamic-tags=0")
toolchain = "1.98.1"
run("rustup", "run", toolchain, "rustc", "--version")
compiler = ["rustup", "run", toolchain, "rustc"]
for source, name in (("hello-safe.rs", "rust-safe"), ("hello-no-asm.rs", "rust-no-asm")):
extra = normal.replace("-Clink-arg=-static ", "")
if name == "rust-safe":
extra = extra.replace("-Clink-arg=-nostartfiles ", "")
path = out / name
run(*compiler, source, *flags.split(), *extra.split(), "-o", path)
verify(path)
codegen = ["-Crelocation-model=static"]
path = out / "rust-normal"
run(*compiler, "hello.rs", *flags.split(), *codegen, *normal.split(), "-o", path)
verify(path, errors=True)
rustc = subprocess.check_output(["rustup", "which", "--toolchain", toolchain, "rustc"], text=True).strip()
for mode, script in (("normal", []), ("minimal", ["-Clink-arg=-Wl,-T,minimal.ld"])):
run("rustup", "run", toolchain, "cargo", "rustc", "--release",
"--target=x86_64-unknown-linux-gnu", "--bin=hello-cargo", "--",
*codegen, *normal.split(), *script, env={**os.environ, "RUSTC": rustc})
path = out / f"rust-cargo-{mode}"
path.write_bytes(Path("target/x86_64-unknown-linux-gnu/release/hello-cargo").read_bytes())
verify(path, errors=True)
[package]
name = "tiny-hello"
version = "0.1.0"
edition = "2024"
[[bin]]
name = "hello-cargo"
path = "hello.rs"
[profile.release]
opt-level = "z"
panic = "abort"
strip = "symbols"
lto = true
codegen-units = 1
[workspace]
[build]
target = "x86_64-unknown-linux-gnu"
rustflags = [
"-Cforce-unwind-tables=no",
"-Crelocation-model=static",
"-Clinker-features=-lld",
"-Clink-arg=-nostartfiles",
"-Clink-arg=-static",
"-Clink-arg=-Wl,--build-id=none,-z,noseparate-code,-z,nosectionheader,--no-eh-frame-hdr",
# "-Clink-arg=-Wl,-T,minimal.ld",
]
export const message: [14]u8 = "Hello, World!\n".*;
pub export fn _start() callconv(.naked) noreturn {
asm volatile (
\\movb $1, %al
\\movl %eax, %edi
\\movl $message, %esi
\\movb $14, %dl
\\syscall
\\xchgl %eax, %ebx
\\xchgl %eax, %edi
\\movb $60, %al
\\syscall
);
unreachable;
}
#![no_std]
#![no_main]
use core::{ffi::{c_char, c_int}, panic::PanicInfo};
#[link(name = "c")]
unsafe extern "C" {
fn puts(s: *const c_char) -> c_int;
fn exit(status: c_int) -> !;
}
#[repr(align(32))]
struct Aligned(u8);
#[unsafe(no_mangle)]
pub extern "C" fn _start() -> ! {
let mut aligned = Aligned(0);
unsafe {
core::ptr::write_volatile(&mut aligned.0, 0);
puts(c"Hello, World!".as_ptr());
exit(0);
}
}
#[panic_handler]
fn panic(_: &PanicInfo<'_>) -> ! { loop {} }
fn main() {
println!("Hello, World!");
}
#![no_std]
#![no_main]
use core::{arch::naked_asm, panic::PanicInfo};
static MSG: [u8; 14] = *b"Hello, World!\n";
#[unsafe(naked)]
#[unsafe(no_mangle)]
extern "C" fn _start() -> ! {
naked_asm!(
"mov al, 1",
"mov edi, eax",
"mov esi, offset {msg}",
"mov dl, 14",
"syscall",
"xchg eax, ebx",
"xchg eax, edi",
"mov al, 60",
"syscall",
msg = sym MSG,
);
}
#[panic_handler]
fn panic(_: &PanicInfo<'_>) -> ! { loop {} }
const linux = @import("std").os.linux;
pub export fn _start() noreturn {
const msg: [14]u8 = "Hello, World!\n".*;
_ = linux.write(1, &msg, msg.len);
linux.exit(0);
}
ENTRY(_start)
PHDRS { image PT_LOAD FILEHDR PHDRS FLAGS(5); }
SECTIONS {
. = 0x400000 + SIZEOF_HEADERS;
.text : SUBALIGN(1) { *(.text._start) *(.text*) } :image
.rodata : SUBALIGN(1) { *(.rodata*) } :image
/DISCARD/ : { *(.comment) *(.note*) *(.eh_frame*) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment