0

Here is the code:

.data
format_in: .string "%ld"
format_out: .string "Number of 1s in the given number %ld = %ld\n"
.text
.globl main
main:
    pushq %rbp
    movq %rsp, %rbp
    subq $16, %rsp
    leaq -8(%rbp), %rsi
    leaq format_in(%rip), %rdi
    movq $0, %rax
    call scanf
    movq -8(%rbp), %rdi
    call rcount1s
    movq %rax, -16(%rbp)
    movq -8(%rbp), %rsi
    movq -16(%rbp), %rdx
    leaq format_out(%rip), %rdi
    movq $0, %rax
    call printf
    leave
    ret

rcount1s:
    pushq %rbp
    movq %rsp, %rbp
    subq $16, %rsp
    cmpq $0, %rdi
    jne .L2
    movq $0, %rax
    jmp .L3

.L2:
    movq %rdi, -8(%rbp)
    andq $1, -8(%rbp)
    sarq $1, %rdi
    call rcount1s
    addq -8(%rbp), %rax

.L3:
    leave
    ret

when i execute it using:

$ as -gstabs task.s -o task.o
$ ld -dynamic-linker /lib64/ld-linux-x86-64.so.2 -e main task.o -o task -lc
$ ./task

It prints segmentation fault.

i've tried to link to scanf library many times, but unsuccessfully`

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • 1
    Use `gcc` to link. – Jester Apr 12 '23 at 19:13
  • You did link against `scanf` in libc successfully, if that had failed `ld` wouldn't have made an executable you could run at all. The problem is `-e main` instead of having CRT code call `main` as a function. This misaligned RSP (RSP % 16 == 0 on entry instead of the expected 8), and there's no return address on the stack so if it did reach the `ret` at the bottom, it would pop argc into RIP and crash that way. – Peter Cordes Apr 12 '23 at 20:44
  • Normally the ELF entry point is called `_start`; naming it `main` doesn't fix anything and is highly confusing; Q&As about calling libc functions from `_start` apply, stuff about writing a `main` doesn't. – Peter Cordes Apr 12 '23 at 20:44
  • [Nasm segmentation fault on RET in \_start](https://stackoverflow.com/q/19760002) / [glibc scanf Segmentation faults when called from a function that doesn't align RSP](https://stackoverflow.com/q/51070716) – Peter Cordes Apr 12 '23 at 20:45

0 Answers0