简体   繁体   中英

segmentation fault and hang in assembly code

I am re-implementing Knuth's program P from Fascicle 1: generate the first 500 primes. The program generates the first 25 primes without problems. That code is below:

$ cat progp.S
/* print the first 500 primes */

#define n       %bx
#define j       %r12
#define k       %r13
#define pk      %r14d

        .data
fmt:    .asciz  "%d\n"
x:      .space 1000

        .text
        .globl  main
        .type   main, @function
main:
        pushq   %rbp
        movq    %rsp, %rbp
        xorq    %rbx, %rbx
        movw    $2, x
        movw    $3, n
        movq    $1, j
Mtwo:
        movw    n, x(,j,2)
        incq    j
Mthree:
        cmpq    $500, j
        je      end
Mfour:
        addw    $2, n
Mfive:
        movq    $1, k
Msix:
        movzwl  x(,k,2), pk
        movzwl  n, %eax
        xorq    %rdx, %rdx
        divl    pk
        cmpl    $0, %edx
        je      Mfour
Mseven:
        cmpl    pk, %eax
        jle     Mtwo
Meight:
        incq    k
        jmp     Msix
end:
        xorq    j, j
loop:
        leaq    fmt, %rdi
        movzwl  x(,j,2), %esi
        call    printf
        incq    j
        cmpq    $25, j
        je      bye
        jmp     loop
bye:
        movl    $0, %edi
        callq   exit
        leave
        ret
        .size   main,.-main
        .end

If you decrease the comparison in Mthree to 25, then the program is fine. Anything higher and the program faults or hangs in printf.

I am assembling it with:

cc -static progp.S

I can also add that without the call to printf, it succesfully generates the first 500 primes as can be seen from putting a breakpoint at "end" in gdb.

$ gdb ./a.out
(gdb) b end
Breakpoint 1 at 0x400531
(gdb) run
Starting program: /home/ben/src/hg/asm/knuth/a.out 

Breakpoint 1, 0x0000000000400531 in end ()
(gdb) p $rbx
$1 = 3571

As soon as I try to call printf, it faults, so I assume I am doing something stupid with the stack.

printf expects in x86-64 a value in %rax that tells the function the amount of the floating point arguments. In your case there are no such arguments, so clear %rax (clearing %eax also clears %rax ). Your program seems to run fine with the change:

...
loop:
        leaq    fmt, %rdi
        movzwl  x(,j,2), %esi
        xor     %eax, %eax
        call    printf
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM