I get a segfault when running this.
I have several questions:
1. How do I print a register, for example eax?
2. Is the factorial function correct? should ret be in the end or could you use it in a cmp-clause?
3. Anything else?
.text # section declaration
# we must export the entry point to the ELF linker or
.global _start # loader. They conventionally recognize _start as their
# entry point. Use ld -e foo to override the default.
#pushl och popl ger problem pga 64bit, anvaend nedanstaende.
#as --32 -o math.o math.s ; ld -melf_i386 -s -o math math.o ; ./math
_start:
#leaves answer in eax, uses eax and ebx
#answer in eax, counter in ebx
#when calling function, N should be in ebx
fac:
movl $1, %eax
fac_loop:
cmp $1, %ebx
jmp fac_end
imul %ebx, %eax
subl $1, %ebx
jmp fac_loop
fac_end:
ret
# write our string to stdout
movl $len,%edx # third argument: message length
movl $5, %ebx # factorial of 5 is what we want to compute
jmp fac # compute it
movl $answer,%ecx # second argument: pointer to message to write
movl $1,%ebx # first argument: file handle (stdout)
movl $4,%eax # system call number (sys_write)
int $0x80 # call kernel
# and exit
movl $0,%ebx # first argument: exit code
movl $1,%eax # system call number (sys_exit)
int $0x80 # call kernel
.data # section declaration
answer:
.ascii "Factorial of 5 is: \n"
len = . - answer
I have several questions:
1. How do I print a register, for example eax?
2. Is the factorial function correct? should ret be in the end or could you use it in a cmp-clause?
3. Anything else?
.text # section declaration
# we must export the entry point to the ELF linker or
.global _start # loader. They conventionally recognize _start as their
# entry point. Use ld -e foo to override the default.
#pushl och popl ger problem pga 64bit, anvaend nedanstaende.
#as --32 -o math.o math.s ; ld -melf_i386 -s -o math math.o ; ./math
_start:
#leaves answer in eax, uses eax and ebx
#answer in eax, counter in ebx
#when calling function, N should be in ebx
fac:
movl $1, %eax
fac_loop:
cmp $1, %ebx
jmp fac_end
imul %ebx, %eax
subl $1, %ebx
jmp fac_loop
fac_end:
ret
# write our string to stdout
movl $len,%edx # third argument: message length
movl $5, %ebx # factorial of 5 is what we want to compute
jmp fac # compute it
movl $answer,%ecx # second argument: pointer to message to write
movl $1,%ebx # first argument: file handle (stdout)
movl $4,%eax # system call number (sys_write)
int $0x80 # call kernel
# and exit
movl $0,%ebx # first argument: exit code
movl $1,%eax # system call number (sys_exit)
int $0x80 # call kernel
.data # section declaration
answer:
.ascii "Factorial of 5 is: \n"
len = . - answer