0

I am develop a very small assembly problem, I try to reduce the crash bug scope.

I found that, if I push some registers to the stack, fscanf will crash.

The pseudocode with no problems:

    set edi/esi/edx/... as right value
    call fscanf

Because I am not sure whether fscanf will change some registers or not, I push the registers to the stack.

The pseudocode with crash problem:

    set edi/esi/edx/... as right value
    push a_register
    call fscanf
    pop a_register

After running call fscanf, it will crash.

supplement:

main.s

.section .rodata    
STR1:
.string "%ld" 
STR2:
.string "1.txt" 
STR3:
.string "r" 
.data  
x:
.long 0          

.globl main
    .type main, @function
.text

main:
    pushq %rbp          
    movq %rsp, %rbp 

    # call fopen
    movq $STR2, %rdi
    movq $STR3, %rsi
    call fopen

    # call fscanf
    movq %rax, %rdi
    movq $STR1, %rsi
    movq $x, %rdx

    # open the pushq/popq will crash !!!!!
    # pushq %r11 
    call fscanf
    # popq %r11

    # call printf
    movq $STR1, %rdi
    movq x, %rsi
    call printf

    leave
    ret 
.size main, .-main

my linux environment (fedora33 x64):

Linux version 5.8.15-301.fc33.x86_64 (mockbuild@bkernel01.iad2.fedoraproject.org) (gcc (GCC) 10.2.1 20200826 (Red Hat 10.2.1-3), GNU ld version 2.35-10.fc33) #1 SMP Thu Oct 15 16:58:06 UTC 2020

build commands:

echo "123" > 1.txt
gcc main.s -lc -m64 -c -g && gcc main.o
./a.out

crash replay:

notice for # open the pushq/popq will crash !!!!!

phuclv
  • 37,963
  • 15
  • 156
  • 475
W.Z.Hai
  • 105
  • 6
  • This doesn't look like assembly code. In particular, `push a_register` is not something I've ever seen before, although I'm happy to be proven wrong if there is a dialect with this specific syntax. In any case, I suggest you post *actual* code. – Robert Harvey Jul 26 '21 at 18:36
  • 1
    If I had to hazard a guess this could be because of stack alignment requirements. If this is 64-bit GCC then at a minimum the stack has to be aligned on a 16-byte boundary at the point of an ABI compliant function (like fscanf etc). Possibly the version that works is aligned properly and the version that doesn't work is not aligned properly. What OS are you targeting (Windows/Linux/MacOS). I assume from the registers you are using that is is Linux or something else using System V 64-bit ABI. Maybe show the code that doesn't work especially if it isn't very big. – Michael Petch Jul 26 '21 at 18:45
  • 1
    Also, learn to use a debugger. If the crash is on an aligned SSE instruction, you know that's the problem. – Jester Jul 26 '21 at 19:29
  • If an extra push makes it crash when everything else is the same, it's almost certainly stack alignment. See the linked duplicate. – Peter Cordes Jul 26 '21 at 20:40
  • Thanks, I know it. – W.Z.Hai Jul 26 '21 at 22:47

0 Answers0