This will be very ammeter question. But I am new to assembly coding so bear with me here.
I am trying to make print function as a library that print numbers in assembly(at&t, x86_64) using syscall (write function / redirect to stdout). The lib file is linked to the main file where the function is called and the print value is stored inside the rax register before calling the function printNumber.
Code inside lib
.global num, printNumber
.section .data
num: .quad 0
.section .text
printNumber:
mov %rax, %r9
mov $10, %r8
printTop:
xor %rax, %rax
xor %rdx, %rdx
mov %r9, %rax
div %r8
mov %rdx, $num
add $0x30, $num
mov %rax, %r9
mov $1, %rax
mov $1, %rdi
mov $1, %rdx
mov $num, %rsi
syscall
cmp $0, %r9
jne printTop
ret
The problem is that it seems that I cannot write to the variable: num.
mov %rdx, num
add $0x30, num
When I use it as lib do i get the error segmentation fault, But when i use it as a normal executable so does it work.
So my question is how do I rewrite the value inside and print it?
num: .quad 0
If there is no way to rewrite values in assembly how do point values to the stdout
mov $1, %rax // Write syscall
mov $1, %rdi // fd where to write/stdout
mov $1, %rdx // Number of values to write
mov $num, %rsi // Pointer to where the output starting from
syscall
Have tried to use set the rbx register with the value instead but wont print anything, I guess that all registers is cleared for syscalls and cannot be used as holders.
mov $num, %rsi
to
mov %rbx, %rsi
//Note: I know that this function will only print unsigned integers reversed, But I am trying to solve the write problem for the moment.
Also I have tried to find solutions, but many are either in x86 or structured as intel.
Main Code
.data
format: .asciz "%d\n"
c: .quad 0
.text
.globl main
main:
push $1337
pop c
push c
pop %rax
call printNumber
movq $60, %rax
movq $0, %rdi
syscall
Build
Lib build.
gcc libCalc.s -no-pie -nostdlib -o libCalc.o
ar rcs ../lib/libCalc.a libCalc.o
Build and link.
gcc -no-pie -o bin/file file.s lib/libCalc.a