-1

I just compiled a simple program that would add two number and will print on console.I have compiled it on RPI board.I think it is compiled fine but when I run I am getting segmentation fault.

.text 
.global main
.extern print
 out:
   .ascii "THE sum is %d\n\0"
 main:
 push {ip,lr}
 mov r0,#5
 mov r1,#4
 add r2,r1,r0 
 ldr r2,=out    
 bl printf
 pop {ip,pc}
 stop: b stop

Is it because I didn't follow the ARM EABI properly?

Could anyone let me know where I am doing wrong?

Amit Singh Tomar
  • 8,380
  • 27
  • 120
  • 199
  • possible duplicate of [ARM to C calling convention, registers to save](http://stackoverflow.com/questions/261419/arm-to-c-calling-convention-registers-to-save) – artless noise Mar 20 '14 at 14:55

1 Answers1

3

The format string for printf (out) needs to go in R0, not R2. Change:

ldr r2,=out

to:

ldr r0,=out

Also if you want to print the sum of 4 and 5 then this should be in R1 (otherwise you're just printing 4). So change:

add r2,r1,r0 

to:

add r1,r1,r0 
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • Thanks Paul I changed as you suggested but still getting same segmentation fault – Amit Singh Tomar Mar 20 '14 at 12:09
  • Why not get a good [working example](http://xivilization.net/~marek/blog/2012/09/30/first-steps-in-arm-assembly/) and start from that? – Paul R Mar 20 '14 at 12:16
  • There's a [link](http://xivilization.net/~marek/blog/2012/09/30/first-steps-in-arm-assembly/) in my comment above. – Paul R Mar 20 '14 at 12:18
  • it worked for me , I just put the out label at the end.I have couple of queries regarding how it works,In x86 the way we do is push the string and resister to the stack before calling the printf function but here we simply loading the string into r0 ,why is it so? – Amit Singh Tomar Mar 20 '14 at 14:35
  • It's a different ABI - parameters are passed in registers. This is common practice on more modern architectures where registers are plentiful, unlike x86, where there are only a few registers, so the x86 ABI uses the stack. – Paul R Mar 20 '14 at 14:42
  • the arm calling convention uses registers first (r0-r3) then if you use those up then use the stack to pass parameters. The x86 traditinoally and still is register starved. as with other low register count instruction sets using the stack all the time is preferred – old_timer Mar 20 '14 at 14:42
  • Thanks @PaulR/dwelch ,got the point you made.One more point to Paul R ,you made a point "Also if you want to print the sum of 4 and 5 then this should be in R1", is it because r1 is a result register not the r2? Why format string needs to be in r0 not in r2? – Amit Singh Tomar Mar 20 '14 at 17:14
  • The function arguments are passed in order, in registers R0-R3, so the format string is the first parameter and goes in R0, the next parameter (your integer sum) goes in R1, then the next (if there was one) would go in R2, etc. – Paul R Mar 20 '14 at 17:16