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