Thursday 20 June 2013

Communicating via C functions

We can call C functions and pass parameters to them. Here we call printf to print a string with numbers.

.section .rodata
string:                             @ the string is defined in the .rodata section
 .asciz "Sum of %d and %d is %d\n"  @ asciz gives us a null-terminated string
.text
 .global main
 .type main, %function
main:
 stmfd sp!, {lr}                    @ stash link register on stack
 ldr r0, =string                    @ store address of start of string to r0
 mov r1, #1                         @ then each parameter to subsequent registers
 mov r2, #41
 mov r3, #42
 bl printf                          @ call the c function to display information
 ldmfd sp!, {pc}                    @ retrieve stashed link register to program counter
 mov r7, #1                         @ set r7 to 1 - the syscall for exit
 swi 0                              @ then invoke the syscall from linux

Note that we change _start to main since we use gcc to assemble and link because we want to link in the C library so that we can access printf.
bob@poland:~/src/asm$ gcc -o printf printf.s
bob@poland:~/src/asm$ ./printf 
Sum of 1 and 41 is 42
bob@poland:~/src/asm$

No comments:

Post a Comment