-1
.global main
.align 2
helloworld:
     .asciz "Hello World"
.text

main:
     ldr r0, =helloworld
     bl puts
     mov r7, #1
     bx lr

I have to use the "bl puts" command in my program and when I run the program the output is Hello World followed by a Segmentation fault and I can't figure out what I did wrong.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Alvin Alic
  • 11
  • 3

1 Answers1

0

You never returned from the program, as Peter Cordes points out your lr register has been overwritten by the call to puts. Thus the program jumps to whatever lr is and just keeps executing until it reaches memory that doesn't belong to it, which it probably does immediately. At that point the os is notified and kills your program giving you the segfault.

  • 2
    `bx lr` is one way for ARM functions return; see https://godbolt.org/z/zxoGjx and the linked duplicates. It's an indirect jump to the address in the link register. If `puts` had restored LR so it was pointing at the instruction after `bl`, you'd get an infinite loop. (So presumably `puts` itself returned with `pop {pr}`, popping a return address that was saved on the stack directly into the program counter, not restoring the caller's `lr`). The actual problem here is failure to save/restore the incoming LR before `bl` overwrites it. – Peter Cordes Sep 29 '20 at 00:23
  • So which command will return from the program because I thought that's what the bx lr did – Alvin Alic Sep 29 '20 at 00:28
  • Yea I know Peter, sorry I just missed the last instruction when I first read it – That_Linux_Guy Sep 29 '20 at 00:30
  • 1
    @AlvinAlic: Look at the linked duplicates at the top of the question. `bx lr` just jumps to LR; you need to make sure that LR holds the right return address when it executes. Look at what C compilers do for functions that call other functions, on https://godbolt.org/z/zxoGjx – Peter Cordes Sep 29 '20 at 00:31