0
extern printf
extern scanf
global main

section .text
main:
    sub rsp, 0x10
    mov rbx, rsp
    add rbx, 0x08
    mov rdi, format1
    mov rsi, rbx
    xor rax, rax
    call scanf
    mov rdi, format2
        mov rsi, [rbx]
        xor rax, rax
        call printf
    add rsp, 0x10
    ret
format1:
    db "%d", 0
format2:
    db "%d", 0xa, 0
value:
    dd 0xa

Above source is same with

#include <stdio.h>
int main(void)
{
    int tmp;
    scanf("%d", &tmp);
    printf("%d\n", tmp);
}

It works well. But I have question. If I change my source code to

extern printf
extern scanf
global main

section .text
main:
    mov rdi, format1
    mov rsi, value
    xor rax, rax
    call scanf
    mov rdi, format2
        mov rsi, [value]
        xor rax, rax
        call printf
    ret
format1:
    db "%d", 0
format2:
    db "%d", 0xa, 0
value:
    dd 0xa

it makes segmentation fault. I think there are no difference between above source code and first one. Did I misunderstand?

5
  • Have you stepped through with a debugger like GDB? Commented Nov 17, 2016 at 2:23
  • In results it says core is dumped, however I can't found core file. Without core file I don't know how to use gdb to analyze program with is written in nasm Commented Nov 17, 2016 at 2:27
  • gdb ./nameofprogram then use layout asm and then layout reg and set a break point on main with b main , start the program with run and then use ni to step instruction by instruction? Or use a graphical frontend for GDB like ddd? Commented Nov 17, 2016 at 2:29
  • When I execute call scanf segmentation fault occur. However I passed format string to rdi and address of value to rsi. So I can't understand why scanf makes error Commented Nov 17, 2016 at 2:37
  • 1
    Okay, this might be a bit difficult to see in a debugger but consider this. You placed value in the .text section. .text is read only. What would happen if you read data into a memory location that is read only? Commented Nov 17, 2016 at 2:39

1 Answer 1

3

In the first code, you're allocating space for a variable (the tmp in your C code, unnamed in the asm code) on the stack and passing the address of it to the scanf function, then passing the value that scanf wrote there to printf.

In the second, you're trying to use a global value allocated in the .text section instead, but .text is read-only by default on most systems. So when scanf tries to write to it, you get a segfault.

Stick a section .data just before value: to put it in the data section instead and it should be fine...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.