I am using Ubuntu 18.04 in a virtual box to run assembly GAS code.
.section .rodata
input_int: .string "%d"
.text
.global main
.type main, @function
main:
movq %rsp, %rbp #for correct debugging -added by the ide
pushq %rbp
movq %rsp,%rbp
subq $8,%rsp
movq $input_int,%rdi
movq %rsp,%rsi
movq $0,%rax
call scanf
movq %rsp,%rdi
movq $0,%rax
call printf
addq $8,%rsp
movq $0,%rax
movq %rbp,%rsp
popq %rbp
ret
This is a very simple which should get an input integer and print the ascii character which corresponds to this integer.
I compile it using gcc:
gcc -m64 -c ./main.s
gcc -m64 ./main.o -no-pie -fno-pie
./a.out
Once reaching to the call scanf
command it throws Segmentation Fault
.
Trying to run a very similar code in the same way DO WORK:
.section .data
f: .string "%d"
x: .long 0
.text #the beginnig of the code
.globl main #the label "main" is used to state the initial point of this program
.type main, @function # the label "main" representing the beginning of a function
main:
movq %rsp, %rbp #for correct debugging # the main function:
pushq %rbp #save the old frame pointer
movq %rsp, %rbp #create the new frame pointer
# Get User Input
movq $0, %rax # clear rax
movq $f, %rdi # load format string
movq $x, %rsi # set storage to address of x
call scanf
# Print Input
movq $x, %rdi
movq $0, %rax
call printf
#return from printf:
movq $0, %rax #return value is zero (just like in c - we tell the OS that this program finished seccessfully)
movq %rbp, %rsp #restore the old stack pointer - release all used memory.
popq %rbp #restore old frame pointer (the caller function frame)
ret #return to caller function (OS)
Which outputs:
>> 97
a
The main difference between the two codes is that one uses an address from the data section and one is saving the variable to the stack of the program.
What may cause this behavior?