From 08e7f3361d845604af658a9b66e0121eaceabf24 Mon Sep 17 00:00:00 2001 From: tocariimaa Date: Fri, 14 Mar 2025 13:31:28 -0300 Subject: [PATCH] articles/assembly.md: add x86-64 factorial assembly --- articles/assembly.md | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/articles/assembly.md b/articles/assembly.md index 77e342b..0aeffa3 100644 --- a/articles/assembly.md +++ b/articles/assembly.md @@ -65,8 +65,33 @@ cc -nostdlib -o hello hello.o ``` ### Factorial (x86-64, Linux) +Returns the calculated factorial as exit code (which is 255 max.) + ```nasm +default rel + +section .text +global _start + +; Compute the factorial of `rdi`, saving the result in `rax` +fact: + mov eax, 1 ; register holding result +.l: + mul rdi ; rax *= rdi + dec rdi ; decrement rdi + test rdi, rdi ; check if rdi = 0 + jne .l ; loop again if rdi != 0 + ret + +_start: + ; x86 registers are sliced, here we assign to edi (32 bit slice) + ; which gets extended to rdi later... + mov edi, 5 + call fact + ; exit syscall + mov rdi, rax + mov eax, 0x3c + syscall ``` -TODO TODO examples for other architectures