memcpy — Copy with rep movsb
Use the rep movsb string instruction for a tight memory copy.
Code
; memcpy(dst, src, n) rdi=dst, rsi=src, rdx=n
section .text
global memcpy
memcpy:
mov rax, rdi ; remember dst for return value
mov rcx, rdx ; count
rep movsb ; copy rcx bytes from [rsi] to [rdi]
ret
; For aligned, large copies use movsq (8 bytes at a time)
global memcpy_aligned
memcpy_aligned:
mov rax, rdi
mov rcx, rdx
shr rcx, 3 ; rcx = qword count (n / 8)
rep movsq
; handle the leftover bytes (n % 8)
mov rcx, rdx
and rcx, 7
rep movsb
retExplanation
rep movsb repeats movsb (copy one byte from [rsi] to [rdi], then advance both pointers) rcx times. On modern x86 the CPU microcode recognizes ERMS (Enhanced REP MOVSB) and runs it at near-peak bandwidth, so rep movsb is now the recommended copy primitive. movsq copies 8 bytes per iteration for tighter loops on older CPUs. The dst pointer is returned in rax to match C's memcpy signature.
More Assembly Snippets
Hello World via Linux syscall
A freestanding x86-64 program that prints and exits using only kernel syscalls.
Function Call Convention (System V AMD64)
Pass args in registers, preserve callee-saved regs, keep rsp 16-byte aligned.
Loop Summation (1..N)
Sum integers 1..N with a counted loop using dec/jnz.
strlen — Scan Until NUL
Compute C-string length by scanning memory until a zero byte.
Bit Manipulation: popcount, ctz, abs
Use BMI/ABM instructions for branchless bit operations.
Read a File via syscalls
open/read/write/close a file using only Linux syscalls.