0

I'm trying to get into Assembly development for the purposes of better understanding lower level development and I'm doing this with my Raspberry Pi Model 4B. I am going through this tutorial at the moment but I wanted to try playing around a bit on my own. I created a really simple add assembly program like so:

.global main
main:
   move r1, #4
   move r2, #3
   add r0, r1, r2
   bx lr

I compiled and linked with the following:

as -o test.o test.s
gcc -o test test.o

and then ran ./test ; echo $? and saw 7 as my output. However when I modified my script to change the add line from add r0, r1, r2 to add r7, r1, r2, I get a 1 as the output. It seems as though I get 1 as my output no matter what register I use but as I understand it the first 15 registers in an ArmV7 architecture as general purpose (with a couple exceptions) so the output register I use should be just fine here. Can someone explain why this returns 1 every time instead of the sum of registers 1 and 2?

1 Answer 1

0

The standard for ARM functions is that a simple return value must be left in R0. When your little program returns to the OS, the OS expects the return value to be in R0.

Furthermore, you should not change the values of registers R4 through R11. If you need to use those registers in a function you should save them on the stack and restore them at the end. That's a general rule for functions, I don't know if the OS absolutely requires that for user programs.

3
  • Hmm. So if I wanted to add four numbers for instance, I couldn't do something like move r1, #1, move r2, #2, move r4, #4, move r5, #5, and then add them by doing add r0, r1, r2, add r3, r4, r5, add r7, r1, r3? Would the ARM way be instead add r0, r1, r2, add r0, r0, r4, add r0, r0, r5? Commented Apr 6, 2021 at 18:20
  • Yes. The result must end up in R0 so you just keep adding values to R0 until you have added them all. Commented Apr 6, 2021 at 19:21
  • Ok cool. Good to know for the future. Appreciate the info!! Commented Apr 6, 2021 at 19:24

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.